Async Await
suggest changeasync is a modifier and await is an operator. Together they free the thread while an operation is in progress, then continue when it completes.
Here is an example that gets a string, then returns its length:
//This method is async because:
//1. It has async and Task or Task<T> as modifiers
//2. It ends in "Async"
async Task<int> GetStringLengthAsync(string URL){
HttpClient client = new HttpClient();
//Sends a GET request and returns the response body as a string
Task<string> getString = client.GetStringAsync(URL);
//Waits for getString to complete before returning its length
string contents = await getString;
return contents.Length;
}
private async void doProcess(){
int length = await GetStringLengthAsync("http://example.com/");
//Waits for all the above to finish before printing the number
Console.WriteLine(length);
}
Here is another example of downloading a file and handling progress and completion. There are two ways to do this:
Method 1:
//This one using async event handlers, but not async coupled with await
private void DownloadAndUpdateAsync(string uri, string DownloadLocation){
WebClient web = new WebClient();
//Assign the event handler
web.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
web.DownloadFileCompleted += new AsyncCompletedEventHandler(FileCompleted);
//Download the file asynchronously
web.DownloadFileAsync(new Uri(uri), DownloadLocation);
}
//event called for when download progress has changed
private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e){
//example code
int i = 0;
i++;
doSomething();
}
//event called for when download has finished
private void FileCompleted(object sender, AsyncCompletedEventArgs e){
Console.WriteLine("Completed!");
}
Method 2:
// This version is async and awaits the download instead of using a completion event.
private async Task DownloadAndUpdateAsync(string uri, string downloadLocation)
{
using (WebClient web = new WebClient())
{
web.DownloadProgressChanged += ProgressChanged;
await web.DownloadFileTaskAsync(new Uri(uri), downloadLocation);
}
}
private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
int i = 0;
i++;
doSomething();
}
private async Task doProcess()
{
await DownloadAndUpdateAsync("http://example.com/file", "local.file");
doSomething();
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents