Wednesday 5 March 2014

Great .NET Framework 4.5 Features async and await

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.
  1. async and await are pair keywords. You cannot use them in a standalone manner.
  2. async is marked on a method. This keyword is just an indicator saying that this method will have the awaitkeyword.
  3. The await keyword marks the position from where the task should resume. So you will always find this keyword in conjunction with Task.

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);
        }
    }
}


Output :



References