Introduction to Async and Await Keywords in C# 5.0

Prior to the introduction of Task Parallel Library (TPL) in .net framework 4.0, writing an asynchronous program was quite a tedious task. One had to write too many lines of code in order to accomplish a simple multi-threaded operation; for example creating wait handles, writing callbacks, complex error handling, etc. In .net framework 4.0, TPL provided developers more abstraction on Asynchronous programming but still the syntax of the asynchronous code was not as simple as a synchronous code to understand. C# 5.0 CTP is now packed with the Async and Await keywords, which allows developers to write asynchronous code but with a structure similar to a synchronous code.

Async and Await keywords

The async keyword can be used as a modifier to a method or anonymous method to tell the C# compiler that the respective method holds an asynchronous operation in it.

The await keyword  is used while invoking the async method, to tell the compiler that the remaining code in that particular method should be executed after the asynchronous operation is completed.

What do You Accomplish with Async and Await Keywords?

This section will list out the things that can be accomplished using async and await keywords in C # 5.0 language.

1. Writing an asynchronous code with a synchronous code structure.

2. By using await you don’t have to worry about modifying the UI elements in an asynchronous operation. There is no need to use the SynchronizationContext object explicitly.

3. In UI applications, the UI will be responsive during the asynchronous operation and will not be grayed out.

4. Exception handling can be done just similar to a synchronous code.

How to Use?

1. Use async modifier to a method, anonymous method or lambda expression, which will have the await operation in it.

public async void GetStringAsync()

2. All method that have the await operations should be marked with the async keyword. This applies to control events as well. Below is an example.

        public async void button1_OnClick(object sender, ClickEventArgs e)
        {
            string value = await new WebClient().DownloadStringTaskAsync(new Uri("http://www.codeguru.com"));
            //Continuation....
 }

3. The await operator can be used only on a method marked with async modifier.

4. An async method can return only void, Task or Task<T>. Basically it should be an awaitable type. An awaitable type is the one that will have a GetAwaiter method returning the awaiter instance, the awaiter in turn has a BeginAwait, EndAwait methods along with an IsCompleted property.

5. Microsoft recommends suffixing the asynchronous method name with ‘Async’ like GetStringAsync instead of GetString.

6. Multiple await statements can be added into a single async method.

Sample Code

Create a console application targeting .net framework 4.5. In the Program.cs file add the code below.

namespace AsyncAndAwaitSamples
{
    class Program
    {
        static void Main(string[] args)
        {
            Program program = new Program();
            program.PrintSumAsync();
 
            ClassA classA = new ClassA();
            classA.DoSomeOtherOperation();
        }
 
        public async void PrintSumAsync()
        {
            int value1 = await GetValueAsync();
            int value2 = await GetValueAsync();
 
            Console.WriteLine("Sum of two random numbers is: {0}", value1 + value2);
        }
 
        private async Task<int> GetValueAsync()
        {
            int random = ComputeValue();
            return random;
        }
 
 
        private int ComputeValue()
        {
            return new Random().Next(1, 1000);
        }
    }
}

Control Flow and Explanation of the Code

When the program is run first the Main method is executed, which makes a call to the async method PrintSumAsync(). In the PrintSumAsync method, once the first GetValueAsync method is called, the main thread returns back to the caller function, which is the Main method where the rest of its code is executed. Later when the GetValueAsync operation completes then the next call to GetValueAsync executes with an await for the asynchronous operation to complete and finally the sum is printed out.

Though the above code is purely asynchronous the structure is pretty much sequential and reduces the code complexity, which is easier to understand. The above example also demonstrates using multiple await statements in a single async method.

In the end, .net framework 4.5 C# compiler is the one that takes the responsibility for emitting the complex IL required for an asynchronous operation from your plain C# code, which uses sync and await keywords.

Happy reading!

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read