Friday, February 3, 2017

await and async

Await and asynch are code marker which mark the position from where control should resume after competition of a task.

Life without await and sync

static void Main(string[] args)
        {
            Method();
            WriteLine("Main Thread");
            Console.ReadKey();           
        }

        private static void Method()
        {
             Task.Run(new Action(Method2));
            Console.WriteLine("New Thread");
        }

        private static void Method2()
        {
            Thread.Sleep(2000);
            Console.WriteLine("Method2");
        }

Output
New Thread
Main Thread
Method2.

If you want to wait after calling Method2 till it finishes than you have to use await and async
Life with await and async

static void Main(string[] args)
        {
            Method();
            WriteLine("Main Thread");
            Console.ReadKey();           
        }

        private static  async  void Method()
        {
            await Task.Run(new Action(Method2));
            Console.WriteLine("New Thread");
        }

        private static void Method2()
        {
            Thread.Sleep(2000);
            Console.WriteLine("Method2");
        }

Output

Main Thread
Method2
New Thread


Now lines after await will not execute until unless function written with await keyword finish.

No comments:

Followers

Link