Parallel.For Loop in .NET 4



Do you have a multiprocessor system? Then, Right click on taskbar and open task manager and click the Performance Tab and notice the performance. You will find something like shown below:

image1.gif

This means there are cores not fully utilized for best performance.

Sequential For loop

for (int i = 0; i < 100; i++)
{
        //Code though independent in each iterations executes sequentially
        a[i] = a[i]*a[i];
}

Multicore-processors machines are now becoming standard. The key to performance improvements is therefore to run a program on multiple processors in parallel.

Introducing TPL

The Task Parallel Library (TPL) is designed to make it much easier for the developer to write code that can automatically use multiple processors. Using the library, you can conveniently express potential parallelism in existing sequential code, where the exposed parallel tasks will be run concurrently on all available processors. Usually this results in significant speedups.

TPL is a major component of the Parallel FX library, the next generation of concurrency support for the Microsoft .NET Framework.

Since the iterations are independent of each other, that is, subsequent iterations do not read state updates made by prior iterations, you can use TPL to run each iteration in parallel on available cores, like this:

Parallel For loop

Parallel.For(0, 100, i =>
                {
                        //This block should contain independent code
                        //It must not update/use value of some variable in
                        //this block from previous iteration
                        //This block should contain a code that takes a huge       
                        //execution time in each iteration
                        //Small complexity code here can result in poor performance
                        a[i] = a[i]*a[i];
                }
            );

image2.gif

Happy Learning...
 

Up Next
    Ebook Download
    View all
    Learn
    View all