C# Asynchronous Programming - Async and Await

Welcome to the Asynchronous Programming in C# 5.0 article series. This is the first presentation of this series. This article explains asynchronous programming in C# 5.0 with code examples. If you're new to asyc programming, this this article is for you. This will be a quick introduction to the async concept, and explaination of the two very important keywords in the world of asynchronous programming, async and await.
What is asynchronous technique?
If you are a senior web developer (at least 5+ years in this field) then you have a lot of experience with the bad response time of web applications. Yes, there was no way (nearly no chance) to change a small portion of content without reloading the entire page (the situation is more pathetic with a slow internet connection). But in modern days, the situation has changed. We can do everything (yes, almost everything) without reloading an entire page or without touching another element. Hence the user's experience and performance has increased. So, how is it done? You are thinking, with AJAX, right? Yes by Ajax, that simply one asynchronous technique to exchange data between the server and the client. So the ultimate goal of AJAX is to call a server method and exchange data from the server without hampering the client. So, clients need not wait for the server's response.
So, asynchronous programming is also all about improvement of performance. Basically, we can implement Ajax in two ways (in ASP.NET). The first option is by updating panel and Ajax toolkit and the second option is by the jQuery Ajax method. (Let's ignore the various third-party JavaScript libraries). In C# 5.0 Microsoft has given us the ability to write our own asynchronous code with C#. Before starting with an example I would like to discuss two master keywords of asynchronous programming, called async and await.
So, let's start. 
This keyword is used to qualify a function as an asynchronous function. In other words, if we specify the async keyword in front of a function then we can call this function asynchronously. Have a look at the syntax of the asynchronous method.
  1. public async void CallProcess()  
  2. {  
  3. }  
Here the callProcess() method is declared as an asynchronous method because we have declared the async keyword in front of it. Now it's ready to be called asynchronously.
Very similar to wait, right? Yes this keyword is used when we want to call any function asynchronously. Have a look at the following example to understand how to use the await keyword.
Let's think; in the following we have defined a long-running process.
  1. public static Task LongProcess()  
  2. {  
  3. return Task.Run(() =>  
  4. {  
  5. System.Threading.Thread.Sleep(5000);  
  6. });  
  7. }  
Now, we want to call this long process asynchronously. Here we will use the await keyword.
  1. await LongProcess();  
I know, if you're relatively new to the concept of asynchronous programming then this dry definition is not enough to understand those concepts. So, let's go through one small example and try to understand those concepts.
Let's create a Windows application and write the following code for it. Here we have created the LongTask() function that will wait for five minutes. Have a look at the function signature; we have declared this function with the async keyword. In other words, we can call it asynchronously. 
  1. using System;  
  2. using System.ComponentModel;    
  3. using System.Threading.Tasks;    
  4. using System.Windows.Forms;     
  6. namespace WindowsFormsApplication1    
  7. {    
  8.     public partial class Form1 : Form    
  9.     {    
  10.         public Form1()    
  11.         {    
  12.             InitializeComponent();    
  13.         }    
  14.         public static Task LongProcess()    
  15.         {    
  16.             return Task.Run(() =>    
  17.             {    
  18.                 System.Threading.Thread.Sleep(5000);    
  19.             });    
  20.         }     
  22.         public async void CallProcess()    
  23.         {    
  24.             await LongProcess();    
  25.             this.listBox1.Items.Add("Long Process finish");    
  26.         }
  28.         private void Form1_Load(object sender, EventArgs e)    
  29.         {    
  30.         }     
  32.         private async void button1_Click(object sender, EventArgs e)    
  33.         {    
  34.              CallProcess();    
  35.              this.listBox1.Items.Add("Program finish");  
  36.         }  
  37.     }   
  38. }  
Here is the samle output.


And the return type of an asynchronous function is Task. In other words, when it finishes its execution it will complete a Task. Each and every asynchronous method can return three types of values.
Void: Means nothing to return
Task: It will perform one operation, a little similar to void but the difference is there.
Task<T>: Will return a task with a T type parameter. (I hope you are familiar with the concept of T)
Let's clarify a few more concepts here.
  • A Main method cannot be defined as asynchronous.
  • It (the Main method) cannot be invoked by the await keyword.
  • If any asynchronous method is not invoked by the await keyword then by nature it will behave like a synchronous method.
  • Function properties should not be defined as asynchronous.
  • The await keyword may not be inside a "lock" section.
  • A try/catch block should not call any asynchronous methods from the catch or finally block.
  • A class constructor or destructor should not define an asynchronous method nor should be called asynchronously. 
In this article we have discussed the basics of asynchronous techniques, I hope you have understood the concepts. In the next article we will understand various return types of asynchronous methods. Keep reading.

Next article >> Asynchronous Programming in C# 5.0 Part Two: Return Type of Asynchronous Method

Sourav Kayal
73 27.7k 23.5m
Next » C# Asynchronous Programming - Return Type of Asynchronous Method