Friday, May 29, 2009

Parallel Programming with .NET Framework 4.0

         In the mscorlib.dll version 4.0.0.0 there are three main namespaces: System.Threading, System.Threading.Tasks and System.Collections.Concurrent. System.Threading contains types like ThreadLocal, ParallelOptions, ParallelLoopState, ParallelLoopResult, Parallel, ManualResetEventSlim to name a few.
         System.Threading.Tasks contains Task, Task, TaskFactory etc to use the Task level parallelism. While the System.Collections.Concurrent contains the generic collections to work with data in thread save manner.
         To get started with TPL, there is simplest class Parallel in .NET Framework 4.0. Lets see what does it have to offer. It has four main methods Parallel.For, Parallel.For<>, Parallel.ForEach<> and Parallel.Invoke. First three methods are, as their names imply, provied to parallelize the loops. These methods have a lot of overloads to cover vast scenarios. While, Parallel.Invoke method has two overloads and just takes the array of Action delegate and invokes them in parallel.
         And here is an example of simplest for method:

Parallel.For takes three arguments: two integers and the third parameter Action delegate. This third delegate parameter is executed parallel on a multi-core machine.

No comments:

Post a Comment