[C#] Multithreading in C# 4 [1] – Task Parallel Library (TPL) API

In .Net Framework 4 (C# 4), a set of types are added to the “System.Threading.Tasks” namespace. Collectively speaking, they are referred to as the “Task Parallel Library“, or TPL.

1. Task Parallel Library (TPL)

As of .NET 4.0, TPL is the recommended way to build multithreaded applications.

The main areas of TPL are

  • Data Parallelism
  • Task Parallelism

Additionally .NET 4 adds a new feature called PLINQ (Parallel LINQ).

2. Data Parallelism

Data parallelism refers to scenarios in which the same operation is performed concurrently on elements in a source collection.

// Sequential version
foreach (var item in sourceCollection)
{
  Process(item);
}

// Parallel
Parallel.ForEach(sourceCollection, item => Process(item));

3. Task Parallelism

Task Parallelism replaces legacy “System.Threading.Thread” and “System.Threading.ThreadPool” types.

TPL works at a higher level of abstraction and provides more intuitive APIs to developers.

Task.Factory.StartNew(() 
  => Console.WriteLine("Hello World!."));

4. PLINQ

Parallel LINQ (PLINQ) is a parallel implementation of LINQ to Objects.

var evenNums = from n in source.AsParallel()
               where ComputeForLongTime(n) > 0
               select n;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s