Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using async/await better then using task.Start() and why?

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?

like image 318
Gerard Avatar asked Dec 25 '22 17:12

Gerard


1 Answers

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 Tasks: 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.

like image 130
Stephen Cleary Avatar answered Jan 09 '23 08:01

Stephen Cleary