Monday, April 02, 2012

.Net 4.0 : Task Parallel Library

Hi There, I am Syam Pinnaka, Dev in IAM services team at Microsoft.

.Net has provided many different ways of Asynchronous programming over various releases. The latest offering that comes with .Net 4.0 is Task Parallel Library (TPL). TPL comes with various benefits over other Async programming models like IAsyncResult or Event based models. The most notable benefits are as follows.

Ability to create parent to child tasks and create complex task hierarchy of dependent tasks.
Ability to Cancel or timeout tasks.
Ability to Wait for one or all tasks.
Continuation options for failed and succeeded tasks.
Ability to catch and handle exceptions.
Exception handling with Async programming is present with both IAsyncResult and Event based models but TPL makes this looks so natural that even a new programmer can start using without much difficulty. As always lets see some example code about how to start using Task Parallel Library.

Creating a task and getting the result is just a few lines of code.

        Task<int> t1 = new Task<int>(CalcSum, 5);
        Console.WriteLine("Sum = " + t1.Result);

        private static int CalcSum(object arg)
            int sum = 0, count = (int)arg;
            for (int i = 0; i < count; i++)
                sum += i;

            Console.WriteLine("In CalcSum, Sum = " + sum);

            return sum;
Note in the above code that a new Task that returns an int is declared. The same can be applied to create a task that returns a void or a custom data type.

Assuming that the “CalcSum” returns a void, in order to  compare “Task” with “QueueUserWorkItem” the below two lines of code are equivalent.

            ThreadPool.QueueUserWorkItem(CalcSum, 5);
            Task t2 = new Task(CalcSum, 5).Start();

Task has methods like .Wait, .ContinueWith and .RunSynchronously which will be handy in certain situations.

Read more: syamp's musings 
QR: Inline image 1

Posted via email from Jasper-Net