async and await are keywords in C# to let code continue executing while waiting on a long operation (like downloading a file) to complete.
Typically, I write synchronous code because it is easier to debug, after it works, then I’ll use async/await.
To make async methods synchronous (i.e. block further code execution until method finishes), add .Result
to the end of the method call. E.g. client.DownloadFileAsync().Result
. If it doesn’t return a value, use .Wait()
instead of .Result
This is how you create a batch of web requests to run in parallel. (You await on Task.WhenAll()
instead of awaiting after each call to DownloadWebsiteAsync()
)
public async Task RunDownloadParallelAsync()
{
List<string> websites = GetWebsiteList();
var tasks = new List<Task<DownloadWebsiteResult>>();
foreach (string site in websites)
{
tasks.Add(DownloadWebsiteAsync(site));
}
List<DownloadWebsiteResult> results = await Task.WhenAll(tasks);
foreach (DownloadWebsiteResult dwr in results)
{
ReportWebsiteInfo(dwr);
}
}
In certain scenarios (esp. in UIs), using await can cause a deadlock. (I’ve experienced this in a Console application using HttpClient
).
To solve this, add a .ConfigureAwait(false)
to the end of the await call.
This video does a great job at explaining async and await. Tim goes through the example of downloading a sequence of files. (Watch it in double speed):
Here’s how to cancel tasks and get progress on the task
get yourself on the email list
comments powered by Disqus