Demistifying async/await

By | August 12, 2013

Microsoft introduced new keywords in C# 5.0 for asynchronous programming. Before C# 5.0 async. programming was only possible with .NET Framework classes. Now it’s implemented in the C# language itself. Here is a simple demo which shows how the keywords can be used.

public async Task<string> DownloadFromWeb()
{
    var client = new HttpClient();
    return await client.GetStringAsync("http://blog.micic.ch");
}

private async void Button1_Click(object sender, RoutedEventArgs e)
{
    var result = await DownloadFromWeb();
    MessageBox.Show("Finished. Length: " +  result.Length);
}

private void Button2_Click(object sender, RoutedEventArgs e)
{
    MessageBox.Show("UI is not freezed");
}

But await! How does it work?
Async / Await
The Button_Click event handler runs the function DownloadFromWeb. DownloadFromWeb executes an HTTP request on a website. The “GetStringAsync” is a asynchronous method. And the DownloadFromWeb awaits the response, the control flow goes back to the caller function at the await statement. In that case: Button_Click.
But because the Button_Click function awaits the response from DownloadFromWeb, the control flow goes back to the parent. Now the control is in the message loop. The thread is not locked.
Now after the GetStringAsync function finished the work, the control flow jumps to the await statement (green arrows) and executes the rest of the DownloadFromWeb. Afterwards, the control flow is again in the message loop. Now because the DownloadFromWeb task has been completed, the control flow jumps to the await DownloadFromWeb (blue arrows) statement and executed the rest of the Button_Click event handler. And while the control flow is in the message loop, the UI thread (in that case) is not freezed! 😉