Jul 16, 2015

Asynchronous Programming in C# 5.0


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

If you don't then this paragraph 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 very good experience with bad response of web applications. Yes, there were no changes (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 is nothing but 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 improved of performances. Basically, we can implement ajax (on another side of asynchronous style) in two ways (in ASP.NET).  The first option is by update panel and ajax toolkit and the second option is by jQuery ajax method. (Let's ignore the various third-party JavaScript libraries).

In C# 5.0 Microsoft has given the facility to write our own asynchronous code by C#. Before starting with an example we 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:

 And the return type of an asynchronous function is Task. In other words, when it finishes it's 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.

No comments:

Post a Comment