This is an introductory post on how to use the async and await keywords in C# to create asynchronous background tasks. It is a common practice to use multi-threading and asynchronous tasks to avoid performance bottlenecks and to keep the application responsive. C# 5.0 has introduced a new model for doing asynchronous programming. To use this feature we need to understand two new keywords, async and await. An important point to note about the async and await keywords is that by themselves these keywords never start a thread. They are a way of controlling execution continuity , and not to be thought of as a way of starting asynchronous code.
The first step is to create an asynchronous method that can be used with async/await. This asynchronous method has to return a task in order to be useful to async/await feature. Also ,the asynchronous method has to start the task it returns. The async keyword implies that the await keyword is now enabled and it also affects how method results are handled. Program execution is asynchronous untill an "await" is encountered following which the the execution becomes asynchronous. An await expression does not block the thread on which it is executing. Rather, it makes the compiler to add the rest of the async method as a continuation on the awaited task. Control then returns to the caller of the async method. When the task completes, it invokes its continuation, and execution of the async method resumes where it was left off.
Asynchronous mode is used for activities that are potentially blocking, such as when the application makes a call to web service or a file system. If such an activity is blocked within a synchronous process, the entire application has to wait for the activity to complete. In an asynchronous process, the application can continue with other work until the blocking activity finishes.
Let us try to see the above using an example where a method calling a web service is used as an example for a long running method. The output of the web-service needs to be displayed in a label , at the end of the call.
Here is the code for calling the long running method accessing web-service on click of button:
private void Button_Click(object sender, RoutedEventArgs e)
// Since we are waiting asynchronously , the UI thread is not blocked by the call to web service.
//This label will be set to "Loading" even before completion of above call
Label.Content = "Loading";
private async void MakeCallToWebService()
string result = await MakeCallToWebServiceAsync("http://www.asyncexample.com");
//When the task is complete the contents returned from the web service will be set in the label
Label.Content = result;
Below is a long running asynchronous method that can be used with async/await