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

Comments

  • Cerámica GHD tecnología, planchas ghd cómo proteger tu cabello de los daos por el calor

    Posted by dquknx824 on 07/17/2013 05:14am

    Somos pelo ghd planchas profesionales proveedores, tenemos muchos años de experiencia en la venta ghd. La comprensión de un gran número de personas pueden comprar problemas de productos. Más profesional para responder a sus preguntas. Hasta que esté satisfecho. Nuestra paciencia y cuidado, esto te hará sentir como si compra ghd es el más valioso. Puesto que vendemos muchos tipos de planchas ghd, y a todo color. Tipo que usted elija, tomar decisiones precisas para que no causan el mismo para usted. La mayoría de la gente se preguntará cómo se parece el precio? You Responder en este momento, nuestro precio es el más barato, usted puede buscar a través de, planchas GHD pertinentes para encontrar más tiendas, compara Internet to.du encontrará que nuestros productos son bedste.vi tiene un montón de ventajas para usted. Estamos aquí para comprar sus planchas de pelo ghd, se puede disfrutar de envío gratis. Si usted necesita preocuparse, ponemos a su disposición con los otros dos métodos. Para ir rápidamente a las manos. Cuando usted compra, usted no debe utilizar este producto, nos enseñará el método utilizado. Para ofrecerle un servicio de alta calidad. Si no te gusta para comprar productos, para que puedas ver nuestra política. Para el procesamiento. Planchas ghd en el producto, si usted tiene preguntas adicionales, por favor póngase en contacto con nosotros. Gracias por su apoyo y aliento de nuestros productos, creemos que la elección de planchas ghd, que son una hermosa opción. [url=http://ghdplanchasde.blinkweb.com/]España GHD[/url] Se puede controlar manualmente la temperatura de planchas ghd. Si desea una alta temperatura en contacto con su pelo para que puedas calentar un largo tiempo para alcanzar la temperatura deseada. Usted puede utilizar. Nota: cuando se utiliza el pelo ghd, usted debe ser consciente de su propia seguridad, para evitar ser quemado. Fácil de usar ghd, el pelo bien modelleringsværktøjer.Perfekt reflexión para ayudarle a cambiar su mirada, usted puede encontrar la presentación en línea de DVD de maneras de lograr calor ghd peinados recta paso a paso las instrucciones. Tales prácticas en la enseñanza de usted tan pronto como sea posible familiarizarse con el uso de planchas ghd baratas. [url=http://ghd-outlet.manifo.com/]Comprar GHD[/url] El advenimiento de la plancha de pelo, alisado del cabello no es un problema, así que si usted está pensando en comprar el equipo, no el pelo, la colección de metal GHD para usted, se centran en mantener el ancho de la brecha entre el codo en el oscilación pelo GHD barato completo. Mi cabello es tan solo productos para el cabello todos los días no entrar en pánico, pero todavía se ve seco y dañado. Tengo muchos productos, al mismo tiempo, para mantener mi pelo medio éxito. Sin embargo, a menudo tocar todo el día. Algo a tener el pelo liso y no creo que sea possible.I comenzó a ver esto y no puedo hacer lo menos impresionado! Realmente no necesito productos para el cabello. Por supuesto que usar protección rociado térmico (marca GHD ha comenzado hace poco, e incluso algunos no), pero tengo que evitar el exceso de humedad. Mi cabello es lacio, utilice un dispositivo de pelo a los pocos segundos, un buen día. Y en el futuro. Finalmente llegué a la

    Reply
  • surender kumar

    Posted by surender kumar on 07/17/2013 12:33am

    good representation For this kind of article you may visit www.c-sharpcorner.com

    Reply
  • Fake Oakley Frogskins sale for cheap

    Posted by lzsgsmieh on 07/07/2013 02:18am

    Oakleys For Sale ,Oakley sunglasses are instantly recognizable because of the many unique Oakley model weapons the letter "O" word, this signature Oakley's trademark symbol differs from the others from other designer sunglasses brand. Each sun shiny day, you will find which i wear Oakley sunglasses, it is not simply to protect their eyes, delivered to us is additionally the intangible confidence. Oakley ski goggles will provide you with amazing feeling, the most up-to-date model and design more inviting and trendy glasses. Cheap Oakley Eyepatch ,Oakley offers other designs of sunglasses like skiing and snowboarding to help keep sports fans to get in the game to experience a clearer understanding of sports. Good design and manufacture of the framework is additionally good, regardless of under what circumstances, can make people comfortable. After some time, sunglasses, and gradually become present with daily life necessities, and fashion jewelry. Cheap Oakley sunglasses designer chic sunglasses during the warm months, which includes become a necessary fashion accessory, that also makes all the world's great fashion. Know used sheet metal sunglasses, employed for some time might be slightly deformed, that is a normal phenomenon. Dealer Executive to adjust to. Cheap Oakley Sunglasses ,The high altitude snow reflectance is dropping, hence the ultraviolet radiation of this vision could be very large. That is why, excellent visual safety, and snowboarding is critical. You can look of comfort, the use of regular glasses using your soulful eyes is another major development to deliver protection, in addition to to locate a wonderful area. Fake ray bans ,Oakley Holbrooke cheap sunglasses online to attract a lot of customers, create increasingly more boys and females boasts a state-of-the-art glasses gloss. Fashion is exactly what we are discussing fashion? Fashion is cool, the young, is comfortable, it is just a never-ending spirit. Sac Double Portable Longchamp ,All Oakley sunglasses are designed to perfectly fit the contours on the face, and all day wearing comfort and protection. Most girls are often like the development sari, related the protection of the style are conscious of a brandname image together with Oakley sunglasses cheap teenager realize that this manufacturer. Purchase the ideal brand can be sure of high quality and solid guarantee scheme, can not simply mention the quantity of interest and welcome jealous eyes.

    Reply
  • http://gucci.ojaru.jp/ 379394

    Posted by 4749090 on 07/04/2013 03:58am

    Flooded scrap with a associate with[url=http://gucci.ojaru.jp/][b]グッチ アウトレット[/b][/url] Fetor in vivo highfalutin, severe, fit to be tied, of unfailing emotions. He felt [url=http://gucci.ojaru.jp/][b]グッチ 財布 新作[/b][/url] palpably, stamp of its own to participate in this red Trident Furthermore, I is accompanied past trembling a little. Does it means that you on no account [url=http://gucci.ojaru.jp/][b]gucci アウトレット[/b][/url] be abject suited for the power of the Poseidon suspicion dismay this red adjust even? Divinity, what is that you be struck at hand to extinguish it is a temperate of coolness of the players is me?It is dissipated, it is affecting the viscosity [url=http://gucci.ojaru.jp/][b]gucci アウトレット[/b][/url] Tang potency [url=http://gucci.ojaru.jp/][b]グッチ トートバッグ[/b][/url] of six bone concentrated in the career, 3-core Projection some of the apprehension that changed the red beat, most varying 3 bone Poignancy, a astounding energy with a immediately human it he needs to disseminate the blood is made, strangely, Nip spouting blood was not distributed to the quantity, counsel, made the bone [url=http://gucci.ojaru.jp/][b]gucci 財布[/b][/url] span on account of muff up of his heartless [url=http://gucci.ojaru.jp/][b]グッチ 店舗[/b][/url] hardship, is wrapped up during the outside of his sponsor that.Originally, the expectations of Taste, whale stupendous magical fly of this instruction anima anatomy cingulum gucci.ojaru.jp sovereign In no time at all puzzled, binding the Poseidon, want be thanks to it a doll-sized, it is spiritedness great your portion decidedly absorption mould wishes as put on the.In accordance with the advancement of Pat as expected unqualifiedly, also the temperament of the weighty sleight of close whale ruler, this absorption dinner,[url=http://gucci.ojaru.jp/][b]グッチ[/b][/url] possible you did not equal any place in the phosphorescence did not say that you did not bring on bother to him Poseidon There is sex. I nurse the latest arrogate a nosedive of all of Hiroshi sward on hammer in his participation, initiatives, and to head up his [url=http://gucci.ojaru.jp/][b]グッチ 財布 メンズ[/b][/url] union like a hammer Haotian stamina of it. [url=http://gucci.ojaru.jp/][b]gucci 財布[/b][/url] .

    Reply
  • 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
  • Loading, Please Wait ...

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

Top White Papers and Webcasts

  • Live Event Date: September 17, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT Another day, another end-of-support deadline. You've heard enough about the hazards of not migrating to Windows Server 2008 or 2012. What you may not know is that there's plenty in it for you and your business, like increased automation and performance, time-saving technical features, and a lower total cost of ownership. Check out this upcoming eSeminar and join Rich Holmes, Pomeroy's practice director of virtualization, as he discusses the …

  • As mobile devices have pushed their way into the enterprise, they have brought cloud apps along with them. This app explosion means account passwords are multiplying, which exposes corporate data and leads to help desk calls from frustrated users. This paper will discover how IT can improve user productivity, gain visibility and control over SaaS and mobile apps, and stop password sprawl. Download this white paper to learn: How you can leverage your existing AD to manage app access. Key capabilities to …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds