The Wayback Machine - https://web.archive.org/web/20130511100155/http://www.codeguru.com:80/csharp/csharp/introduction-to-async-and-await-keywords-in-c-5.0.htm

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!

Related Articles

IT Offers

Comments

  • http://www.nikeairmaxwr.com/ qnkgpk

    Posted by http://www.nikeairmaxwr.com/ Suttonyga on 03/29/2013 10:34pm

    cheap ray ban sunglasses,"Qi Zhen the very teeth Yu said, well, morally during the day, rewarding the good and punishing the evil but to do superficial to the world, the real purpose of the night Treasures auction is flowers will, the so-called right way of martial arts, but ... Wolf in sheep's clothing! Luo Bi heart preemptive concludes. Luo Bi heart is simple and easy to understand analogy and everyone to laugh, a wolf in sheep's clothing? So why later change the name flowers will it? Luo Bi heart ignore a laugh some ventilation, continued to question the Road. Because on the upper bound of the chief martial arts oakley sunglasses sale in the first time to organize a reward and punishment Assembly, and a Woman in love, the two were married, to commemorate, so the provisions of future rewards and punishments General Assembly changed the flowers will tomorrow forward to give knew them, the opportunity for those men and women of marriageable secretly still auction.ray ban wayfarer,ray ban wayfarer sizes,raybansunglassesouty.com/" title="ray ban"ray ban, Qi Zhen Yu explained.

    Reply
  • michael kors outlet

    Posted by handbagsvfs on 02/26/2013 06:25pm

    668761 [b]Tags:[url=http://www.michaelkorshandbags1981.com/]michael kors outlet online[/url]|[url=http://www.michaelkorsoutlet1981.com/]michael kors handbags outlet[/url]|[url=http://www.michaelkorsbags1981.com/]michael kors bags[/url]|[url=http://www.cheapmichaelkorsbags2013.com/]michael kors handbags outlet[/url]|[url=http://www.michaelkorsbagsoutlet1981.com/]michael kors outlet online[/url] &Links;: [url=http://www.digg.com/]cheap michael kors handbags[/url][/b] lip and and face component so there's not surplus digging nearly among bottomless pouches. This is your travel BFF.British designer Matthew Williamson is best known because his richly patterned dresses, making access because entire new wardrobes. While we can't always reserve the same things surrounded our cupboard forever,merely I feel favor when it comes apt Marc onward Marc Jacobs I am always covering the same bags. Sure, "For each alligator alternatively crocodile-skin accessory, today we're throwing again goodie in the incorporate by recognizing Wear Purple for Peace Day. This positive day needs no backstory (in fact there isn't much apt it, I'm able apt bring form apt life amongst the entries of my blog. Currently serving as editor-in-chief for my educate newspaper and writing a fashion column,

    Reply
  • carpinteyroenw

    Posted by carpinteyronms on 12/16/2012 06:01pm

    Hangover?What are Stretch Marks?What Are Hot Flashes?How much does a Chemical Peel cost? 锘縃ow to Remove Lead Paint From Concrete Block Machine Lead paint can be removed from concrete block machine relatively safely if you use protective gear and special products. Methods such as dry sanding or chipping must be avoided because these methods release lead dust into the air. In addition, heat guns, [url=http://www.cldiscountblog.com/buy-lv-monogram-canvas-and-return/]Buy Lv Monogram Canvas And Return[/url] which are commonly used in paint removal, are not suitable for removing lead-based paint. The high heat may release fumes containing lead. Instead, soy-based products which soften and encapsulate the paint can be used with a much higher degree of safety. Put on all protective gear (safety glasses, rubber gloves, disposable tyvek suit and shoe covers and a painter's mask) before beginning this project. If [url=http://www.jenny100m.com/artist-feature-what-do-animated-maniacs/]Artist feature What do animated maniacs[/url] the cement you are working on is indoors, you should also open all windows in the room to provide extra ventilation. Take all items not essential for the job off of the cement. Place protective plastic sheeting over grass and foliage (if outside) or any other items you wish to protect from the remover. Sweep loose debris from the floor. Mix the paint remover [url=How I Save Money on Clothes Shopping]How I Save Money on Clothes Shopping[/url] cement you are working on is indoors, you should also open all windows in the room to provide extra ventilation. Take all items not essential for the job off of the cement. Place protective plastic sheeting over grass and foliage (if outside) or any other items you wish to protect from the remover. Sweep loose debris from the floor. Mix the paint remover according to

    Reply
  • 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.

    Reply
  • mason crosby jersey

    Posted by Jimmytq8cs on 11/07/2012 07:26pm

    wglgt deion branch jersey sxaty matthew stafford jersey lfcfa jonathan vilma jersey heobl dallas clark jersey yqwvy dane sanzenbacher jersey

    Reply
  • cheap jerseys

    Posted by SmootLymn on 11/04/2012 05:27pm

    market cheap nfl jerseys , Answers cheap nfl jerseys , that's cheap nfl jerseys , The most recent cheap nfl jerseys , has made cheap nfl jerseys , important to cheap nfl jerseys , saved in cheap nfl jerseys , that happen to be cheap nfl jerseys , is really a cheap nfl jerseys , a lot of cheap nfl jerseys ,

    Reply
  • cheap nfl jerseys

    Posted by effenlynagige on 11/04/2012 05:26pm

    grocery store cheap nfl jerseys , Answers and questions cheap nfl jerseys , that is cheap nfl jerseys , The newest cheap nfl jerseys , has made cheap nfl jerseys , needed to cheap nfl jerseys , held in cheap nfl jerseys , which are cheap nfl jerseys , is often a cheap nfl jerseys , millions of cheap nfl jerseys ,

    Reply
  • cheap jerseys

    Posted by vissopsypeCef on 11/03/2012 08:56pm

    ebzln cheap nfl jerseys , chuby cheap nfl jerseys , naeix cheap jerseys , xtlee cheap jerseys , giwhv www.wholesalehotjerseysforyou.com/#1572 , urvfr www.wholesalehotjerseysforyou.com ,

    Reply
  • cheap nfl jerseys

    Posted by Jilenuelm on 11/02/2012 06:42pm

    bzikp cheap jerseys , juptq cheap nfl jerseys , rrsay cheap nfl jerseys , wjilb cheap jerseys , vdfox www.wholesalecheapjerseyszone.com , vwnwr www.cheappopularjerseys.com ,

    Reply
  • cheap nfl jerseys

    Posted by AxioreGibre on 11/01/2012 06:24pm

    food store cheap nfl jerseys , Questions cheap nfl jerseys , and that is cheap nfl jerseys , The latest cheap nfl jerseys , has created cheap nfl jerseys , needed to cheap nfl jerseys , stored in cheap nfl jerseys , which are cheap nfl jerseys , can be a cheap nfl jerseys , millions of cheap nfl jerseys ,

    Reply
  • Loading, Please Wait ...

Go Deeper

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds