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?