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.
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.
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
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:
Here is sample output:
- 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