Introduction to Async and Await Keywords in C# 5.0


Application Security Testing: An Integral Part of DevOps

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"));

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();
            ClassA classA = new ClassA();
        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!

Related Articles


  • Your code is bad and you should feel bad

    Posted by asdasd on 11/27/2012 01:59am

    Sorry but your sample Code is really bad and in no way asynchronous. Everything is executed synchronously! Just use your Code in a Winforms-Project and include a Thread.Sleep into ComputeValue. You will see that your code doesn't do what you've intented. There is a missing call to Task.Run or Task.Factory.StartNew to ultimately span an async operation.

  • Nicely Done!

    Posted by Robert Percy on 08/12/2012 09:24am

    You took a 2+2 example of the Await and Azync Functions and left it like that. It was not converted into an Einstien Outer-space formula. I Like It. You did a very good job on this short, but very informative, article. Now I do not need to buy a 600 page book on something you explained in a few hundred words. Keep up the good work.

  • You must have javascript enabled in order to post comments.

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • As all sorts of data becomes available for storage, analysis and retrieval - so called 'Big Data' - there are potentially huge benefits, but equally huge challenges...
  • The agile organization needs knowledge to act on, quickly and effectively. Though many organizations are clamouring for "Big Data", not nearly as many know what to do with it...
  • Cloud-based integration solutions can be confusing. Adding to the confusion are the multiple ways IT departments can deliver such integration...

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date
We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.