Compare the following two methods:
static async Task<int> DownloadAsync(string url)
{
var client = new WebClient();
var awaitable = client.DownloadDataTaskAsync(url);
byte[] data = await awaitable;
return data.Length;
}
usage: Task<int> task = DownloadAsync("http://stackoverflow.com");
static Task<int> Download(string url)
{
var client = new WebClient();
var task = client.DownloadDataTaskAsync(url);
byte[] data = task.Result;
return Task.FromResult(data.Length);
}
usage:
Task task = new Task(() => Download("http://stackoverflow.com"));
task.Start();
As far as I can see both methods run asynchronously. My questions are:
Is there any difference in behavior between the two methods?
Why do we prefer async-await other then it being a nice pattern?
The two methods you post are completely different.
DownloadAsync
is a truly asynchronous method. This means that while the data is downloading, there are no threads blocked on that asynchronous operation.
Download
synchronously blocks the calling thread by calling Task.Result
. I explain on my blog why Result
should not be used with asynchronous Task
s: in the general case, it can cause deadlocks. But let's assume there's no deadlock. You then call it from a TPL task, so it blocks the task thread (most likely a thread pool thread). While the data is downloading, that task thread is blocked on that asynchronous operation.
So, DownloadAsync
is more efficient.
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