Translate

Wednesday, 3 October 2012

Async and await - C# 5


using System;
using System.Threading;
using System.Threading.Tasks;

namespace AsyncAwait
{
    class Program
    {
        static int? addTaskId, printTask,taskMethod2Id;
        static int x;
        public static async Task TaskMethod2()
        {
            Console.WriteLine("Task Method 2 called");
            await Task.Factory.StartNew(() =>
                {
                    printTask = printTaskId();
                    Task.Factory.StartNew(()=>
                        {
                        x=add(9,8);
                        addTaskId = Task.CurrentId;
                });
                });
            return Task.CurrentId;
        }
        static int add(int a, int b)
        {
            return a + b;
        }
        public static async void MainTaskMethod()
        {
              await Task.Factory.StartNew(async () =>
                {
                    taskMethod2Id = await TaskMethod2();
                });
        }
        public static int? printTaskId()
        {
            return Task.CurrentId;
        }
        static void Main(string[] args)
        {
           MainTaskMethod();
           Thread.Sleep(15);
           Console.WriteLine("Task ids are {0} and {1} and value of add result is {2}", addTaskId, printTask,x);      
            Console.Read();
        }
    }
}

1. taskMethod2Id  will be null because the Main() method cannot be async-ed and hence the result cannot be await-ed.
2. Remove or comment the "Thread.Sleep(..) " call and see how it works! 
3. To use await inside a lambda expression, mark the lambda with the async keyword.
4. If you remove the await keyword from inside the TaskMethod2

            await Task.Factory.StartNew(() =>
                {
the output for addTaskId will be "3" and for printTask, "2" and if you use await, it will be "2" and "1". 
5. The usage of the async does not mean asynchronous processing, of the method or the lambda,  automatically but that you can enable "await"-able states within the method or the lambda expression. 
Happy C# 5 programming! :)

No comments: