Trying to understand async-await
in C#, and a bit stuck in a "chicken and egg" problem, maybe.
Does an async
method need to call another async
for it to be asynchronous?
As a high level example, I'm trying to do a simple write to the file system, but not sure how I can make this task awaitable, if at all.
public Task<FileActionStatus> SaveAsync(path, data)
{
// Do some stuff, then...
File.WriteAllBytes(path, data); // <-- Allow this to yield control?
// ... then return result
}
That line of code is being called within a method that I'm trying to make asynchronous. So while the file is being written, I'd like to yield control to the application, but not quite sure how to do that.
Can someone enlighten me with a very high-level example of how I could write a file to the file system in an async
way?
Consider using the 'await' operator to await non-blocking API calls, or 'await Task. Run(...)' to do CPU-bound work on a background thread. SynchronousAsync. The calling code will still be able to await this method, but since the task returned by the Task.
The differences between asynchronous and synchronous include: Async is multi-thread, which means operations or programs can run in parallel. Sync is single-thread, so only one operation or program will run at a time. Async is non-blocking, which means it will send multiple requests to a server.
Solution A If you have a simple asynchronous method that doesn't need to synchronize back to its context, then you can use Task. WaitAndUnwrapException : var task = MyAsyncMethod(); var result = task. WaitAndUnwrapException();
The call to the async method starts an asynchronous task. However, because no Await operator is applied, the program continues without waiting for the task to complete. In most cases, that behavior isn't expected.
Does an async method need to call another async for it to be asynchronous?
Usually that is the case as async goes all the way to the bottom of the call-stack and ends at the lowest place which is actually making the IO operation. In your case, you're using File.WriteAllBytes
which is a blocking synchronous call. You can't magically make it asynchronous.
Can someone enlighten me with a very high-level example of how I could write a file to the file system in an async way?
To do that you need to be using a mechanism which exposes an asynchronous API, such as FileStream
:
public async Task<FileActionStatus> SaveAsync(string path, byte[] data)
{
using (FileStream sourceStream = new FileStream(path,
FileMode.Append, FileAccess.Write, FileShare.None,
bufferSize: 4096, useAsync: true))
{
await sourceStream.WriteAsync(data, 0, data.Length);
}
// return some result.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With