async and await
This feature has been oversold and every .NET evangelist has talked about it. But this is still my favorite and you will come to know why in a few lines from here.
async
and await
are markers which mark code positions from where control should resume after a task (thread) completes.async
andawait
are pair keywords. You cannot use them in a standalone manner.async
is marked on a method. This keyword is just an indicator saying that this method will have theawait
keyword.- The
await
keyword marks the position from where the task should resume. So you will always find this keyword in conjunction withTask
.
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Task_asyncandawait
{
class Program
{
static void Main(string[] args)
{
Add(5,6);
Sub(5, 6);
Mul(5, 6);
Console.WriteLine("Main method");
Console.Read();
}
public static async void Add(int a,int b)
{
await Task.Run(new Action(LongTask));
Console.WriteLine("Add Method
= "+ a + b);
Console.WriteLine("Add Thread");
}
public static async void Sub(int a, int b)
{
await Task.Run(new Action(LongTask));
Console.WriteLine("Sub Method
= "+ (a - b));
Console.WriteLine("Sub Thread");
}
public static async void Mul(int a, int b)
{
await Task.Run(new Action(LongTask));
Console.WriteLine("Mul Method
= "+ a * b);
Console.WriteLine("Mul Thread");
}
public static void LongTask()
{
Thread.Sleep(10000);
}
}
}