Introduction
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 async programming, then this is the article is for you. This will be a quick introduction to the async concept, and explanation of 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 to change a small portion of the 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 have increased. So, how is it done? You are thinking, with AJAX, right? Yes with AJAX, simply one asynchronous technique is needed 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. The 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 the 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 Function in C#
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 Function in C#
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();
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 the sample output.
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:
- The 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 the 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 it 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.
To better uunderstand this article please read next parts also.