Asynchronous Programming in C# 5.0 Part One: Understand 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 suitable examples.

I hope you have had good experiences with C# and you already understand the concept of asynchronous technique, what it is, and what its value is in applications.

If you don't then this article is for you. This will be a quick explanation of the entire concept, then we will explain two very important keywords in the world of asynchronous programming, called 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.

Async

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.

public async void CallProcess()

{

}

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.
 
Await

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.

public static Task LongProcess()

{

    return Task.Run(() =>

    {

        System.Threading.Thread.Sleep(5000);

    });

}

Now, we want to call this long process asynchronously. Here we will use the await keyword.

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.
 

using System;

using System.ComponentModel;

using System.Threading.Tasks;

using System.Windows.Forms;

 

namespace WindowsFormsApplication1

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

 

        public static Task LongProcess()

        {

            return Task.Run(() =>

            {

                System.Threading.Thread.Sleep(5000);

            });

        }

 

        public async void CallProcess()

        {

            await LongProcess();

            this.listBox1.Items.Add("Long Process finish");

        }

 

        private void Form1_Load(object sender, EventArgs e)

        {

        }

 

        private async void button1_Click(object sender, EventArgs e)

        {

             CallProcess();

             this.listBox1.Items.Add("Program finish");

        }      

    }

}
 
Here is sample output:

async-and-await-1.jpg

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.

Conclusion

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 >>