Saturday 23 November 2013

An Alternative to Threads: Tasks in Task Parallel Library

.NET 4 introduces an alternative to Threads, known as Tasks, which is part of mscorlib. This is the new and preferred way to do asynchronous programming in .NET.

Task factories are the new tool of choice to create Tasks (the new incarnation of Threads) and start them immediately. They can also be used to create task continuations. A continuation task is a task that invokes another task on completion. The task that completes before the next task is called is known as the antecedent.

A task can be created using the syntax:  Task.Factory.StartNew( () => ...).

The above syntax says we must supply a delegate as a lambda expression a.k.a. anonymous function, or object of type Action, to the StartNew method of the Factory object (default instance of TaskFactory).

The StartNew method returns an object of type Task.  Task.WaitAll takes a list of tasks and blocks until all the tasks specified have completed. It can be called with an optional extra argument, specifying the wating time timeout in milliseconds (stored as an Int32, implemented as a struct in mscorlib, though you already knew that).

Because now we are talking about tasks not threads, we can no longer talk about multithreading, and to talk about multitasking seems rather an over-use of the term. Therefore, we need a new term, and for that we have been given the new conjunction, Task parallelism. 

No comments: