Parallel.For Loop in .NET 4

Do you have a multiprocessor system? Then, Right-click on the taskbar and open the 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
  1. for (int i = 0; i < 100; i++)  
  2. {  
  3.         //Code though independent in each iterations executes sequentially  
  4.         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
  1. Parallel.For(0, 100, i => {  
  2.     //This block should contain independent code  
  3.     //It must not update/use value of some variable in  
  4.     //this block from previous iteration  
  5.     //This block should contain a code that takes a huge         
  6.     //execution time in each iteration  
  7.     //Small complexity code here can result in poor performance  
  8.     a[i] = a[i] * a[i];  
  9. }); 
image2.gif
 
Happy Learning...


Recommended Free Ebook
Similar Articles