Task Parallel Library in .NET

With .NET 4.0, new concept is introduced – Task. Task is part of Task Parallel Library (TPL), which is a new collection of classes that focus on parallel programming as well as offer light weight object compared to traditional threading system.

When user/process creates a new Thread then the whole process goes with it for creating queue, managing life cycle, handling thread local storage, etc. You can use ThreadPool to delegate all these work and avoid the overhead of creating new Thread as ThreadPool manages it.

Drawback while using classic ThreadPool is that you can not cancel the work item that has been queued with the ThreadPool or get returned result from work item easily. So, the new TPL architecture has got solutions to all these problems and also comes with other useful features.

A TPL Task uses ThreadPool internally. Most of the time, we are using default scheduler so Tasks allocate threads using ThreadPool which handles creation of threads for the particular task. There is lot of heavy processing done by TPL behind the scenes.

On a pure technical base, we can define Task as an interface for passing work to be done, storing state of task, exception, continuation of tasks. The work will be done by the scheduler used not by the ThreadPool.

One another great feature about TPL is that it aims to use each core of CPU so no core will be idle. Again, it used threads only but user need not to be part of any thread creation and handling.

Tasks over Threads

When we execute program instructions on multiple threads, its not assured that the threads are separated. Parallel means the work is spread across multiple processors to maximize computational speed. Tasks are tuned for leveraging multicore processors.

Task provides following powerful features over thread.

If system has multiple tasks then it makes use of the CLR thread pool internally, and so we do not have the overhead associated with creating a dedicated thread using the Thread. Also it reduces the context switching time among multiple threads.

Task can return a result. There is no direct mechanism to return the result from thread.

Wait on a set of tasks, without a signaling construct.

We can chain tasks together to execute one after the other.

Establish a parent/child relationship when one task is started from another task.

Child task exception can propagate to parent task.

Task supports cancellation through the use of cancellation tokens.

Asynchronous implementation is easy in task, using ‘async’ and ‘await’ keywords.

Asynchronous Programming with Async and Await

Using asynchronous programming, dot net developers can avoid performance congestion and achieve good responsiveness of application. Traditional ways of writing asynchronous application can be complex and also make them hard to debug and maintain.

NET Framework 4.5 and Windows Runtime has got the feature of asynchronous programming with release of Visual Studio 2012.

Asynchronous programming is effective when your application needs access to more web resources. Now, application does not need to wait in case of any web resource access is delayed or became slow. Application can continue with other work.

You can implement asynchronous programming using Async and Await keywords.

Task Parallelism VS Data Parallelism

Task parallelism does the execution of computer programs across multiple processors on same machine or multiple machines. It focuses on executing different operations in parallel to fully utilize the available computing resources in form of processors and memory. Data parallelism focuses on distribution of data sets across the multiple computation programs. In this form, same operations are performed on different parallel computing processors on the distributed data subset.

Parallel.Invoke to Execute Parallel Operations

Parallel.Invoke method is used to perform parallel operations. It is mainly useful when you have situation of accessing same data source but with different operations. Invoke method can run this kind of operation easily with no modification to data source.

C#

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

Parallel.Invoke(()=>

{

Console.WriteLine("Begin Opearation One...");

OpearationOne();

},

()=>

{

Console.WriteLine("Begin Operation Two...");

OperationTwo();

},

()=>

{

Console.WriteLine("Begin Operation Three...");

OperationThree();

});

ParallelEnumerable.AsParallel Method (Ienumerable)

AsParallel Query expressions can be run in parallel. With this extension method, user can enable parallel threads to improve performance. AsParallel will not have great results on all kinds of queries. For small collections, AsParallel will be slower.