Saturday, August 6, 2016

3.Asynchronous programming using Async and Await (Dependent Async Operation)


Dependent Asynchronous operation example:

In below example we have 3 tasks t1,t2 and t3. Task  t1's result will be used in t2 and t2's result will be used in t3.
Operation t1 will take more time to complete as I have used Thread.Sleep(10000) so it will take 10 second to complete it's operation.


class DependentAwait
    {
        public static void Main()
        {          
            Task t =  M1Wrapper();

            Console.WriteLine("Final Result=" + t.Result);
            Console.ReadKey();
        }
        public async static Task M1Wrapper()
        {
            Task t1 = Task.Run(() => { Thread.Sleep(10000);  return M1(4, 5); });
            await t1;
            Task t2 = Task.Run(() => M1(t1.Result,5));
            await t2;
            Task t3 = Task.Run(() => M1(t2.Result,5));
            return await t3;
       
        }
        public static int M1(int a,int b)
        {
            return a + b;
        }
     
    }

Output : Result of above program would be 19.

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 ...