Saturday, August 6, 2016

2. Asynchronous programming using Async and Await


Please read "Asynchronous programming using Async and Await" before reading it.

Asynchronous method with multiple await :

class AsyncAwaitTest
    {
        public static void Main()
        {            
            Task t =  M1Wrapper();
            //Other Operation ....
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine("Main i=" + i);
            }
            Console.ReadKey();
        }
        public async static Task M1Wrapper()
        {
            Task t1 = Task.Run(() => M1());
            Task t2 = Task.Run(() => M2());
            Task t3 = Task.Run(() => M3());
            await t1;
            await t2;
            await t3;
        }

        public static void M1()
        {
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine(" Method M1: i=" + i);
            }
        }
        public static void M2()
        {            
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine(" Method M2: i=" + i);
            }
        }
        public static void M3()
        {           
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine(" Method M3: i=" + i);
            }
        }


    }

Output:


No comments:

Post a Comment

C# Record type: Something to remember while using record types

  Record in c# provide a concise and expressive way to create immutable data types, record is a keyword in c#, we can use this keyword with ...