Basics of async and await

In .NET 4.5 Microsoft added the async and await keywords.

Important: By prefixing a method with the async keyword we’re telling the .NET compiler that you want to use the await keyword. The async keyword does NOT mean your method is automatically asynchronous, i.e. the compiler will not automatically assign a thread to it or a task. It simple indicates that the compiler to compile the code so that it can be suspended and resumes at await points.

If you wrote a simple async method which carried out some long running calculation the method would still be synchronous. Even if we await the result (you can have a async method without an await but this is equivalent to any other type of synchronous method and will result in compiler warnings).

So what’s the point of async and await ?

We basically use async on a method to allow us to use await. If there’s no async then we cannot use await. So the await is really where the magic happens.

The await keyword can be thought of as a continuation on a Task. It allows us to break a method into parts where we can suspend and resume a method. Below is an example of a call to some LongRunningTask

// simulation of a method running on another thread
private Task LongRunningTask()
{
   return Task.Delay(10000);
}

private async void Button_Click(object sender, RoutedEventArgs e)
{
   textBox.Text = "";
   await LongRunningTask();
   textBox.Text = "Completed";
}

What happens with the above is that a button click event takes place and the textbox is set to an empty string, then a LongRunningTask occurs on a different task. The await keyword suspends operation of this method now until the LongRunningTask completes but the UI in this case remains responsive. When the LongRunningTask ends the text is set to “Completed”. As the button was called from the UI thread the code after the await line is run on the UI thread, i.e. the synchronization context for the code after the await line is the same as the synchronization context used before the await line.

An async method may have one of three types of return, a Task (non-generic) and Task<> (generic) and a void. The return should be either of the Task objects to allow for a calling method to await the method. Void should only be used for things like event handlers.

We can implement code similar to await using Task ContinueWith, but one neat feature of async/await is in WinForms/WPF The code after the await is executed on the same thread as the async method was called on. ContinueWith, by default, is executed on another thread. Obviously this feature of async/await is very useful with the likes of WinForms as a button click might await a webservice call or the likes, then return onto the GUI thread upon return.