Task Parallel Library in .NET 4.0 – Part 1

Nov 13th, 2010 | By | Category: Framework & Libraries

In one of my earlier posts about the Parallel Programming Extensions in .NET 4.0 I had briefly mentioned about the Task Parallel Library one of the most critical components of the Parallel Extensions.It primarily consists of the APIs provided under System.Threading& Sytem.Threading.Tasks.It uses the CLR Thread Pool behind the scenes and some  sophisticated algorithms to assign number of threads to maximize performance.It provides more programmatic control than thread or work item to

  • Create/Start Tasks
  • Return result values from tasks
  • Chain Multiple Tasks
  • Create Nested & Child Tasks
  • Handle Exceptions

The following snippet shows how to create and start/run a task.

public void RunSimpleTaskDemo()
{ 

    Task t1 = new Task(() => M1()); 

    t1.Start(); 

}
public void M1()
{
    Console.WriteLine("Thread Id is {0}", System.Threading.Thread.CurrentThread.ManagedThreadId);
    System.Threading.Thread.Sleep(100);
    Console.WriteLine("Method M1 Called");
}

The task class has a constructor which accepts a Action delegate as shown below.

public Task(Action action)

In the above example we have passed a Lambda expression to the delegate which internally calls the method M1.On calling the method Start the task actually starts executing.

Similarly, there is a generic version of this class (Task<TResult>) which is used to return results of type TResult from the tasks as shown below:

public void RunTaskDemoWithResults()
{ 

    Task<int> t1 = new Task<int>(() => M3()); 

    t1.Start(); 

    Console.WriteLine("T1 Result: {0}", t1.Result); 

}
public int M3()
{
    return 3;
}

The result can be obtained from the property Result of Task<TResult> class.This is a blocking call and waits for the task to complete and returns the result.

The Task class exposes a method ContinueWith with the following signature:

public void RunTaskContinueDemo()
{
    Task<int> t1 = new Task<int>(() =>
                                    {
                                        Console.WriteLine("Task 1");
                                        return 1;
                                    }
                                 );
    Task<int> t2 = t1.ContinueWith<int>((t) =>
                                            {
                                                Console.WriteLine("Task 2");
                                                int j = t.Result;
                                                return j + 1;
                                            }
                                );
    t1.Start(); 

    Console.WriteLine("Results of T2 {0}",t2.Result);
} 

Here, after the task t1 is completed the task t2 automatically starts executing the lambda expression passed as parameter to the ContinueWith method.This lambda expression receives Task t1 as it’s parameter.So t2 can make use of any results that are produced while execution of t1.This known as Task Chaining and provides a mechanism to provide callback methods. 

In our next post we will take a look at Nested/Child tasks and Task Cancellation.


Kick It on DotNetKicks.com
Tags: , ,
  • http://topsy.com/trackback?url=http%3A%2F%2Fcodingndesign.com%2Fblog%2F%3Fp%3D195&utm_source=pingback&utm_campaign=L2 Tweets that mention Task Parallel Library in .NET 4.0 – Part 1 – Coding N Design — Topsy.com

    [...] This post was mentioned on Twitter by Sankarsan Bose, Sankarsan Bose. Sankarsan Bose said: RT @sankarsan Task Parallel Library in .NET 4.0 – Part 1 http://bit.ly/ci56hA #dotnet #CSharp #ParallelProgramming [...]

  • http://codingndesign.com/blog/?p=198 Task Parallel Library in .NET 4.0 – Part 2 – Coding N Design

    [...] my last post I had started a discussion on Task Parallel Library introduced as part of .NET 4.0.In this post [...]