Monday, December 27, 2010

What is the difference between For(C#) and Parallel.For(.NE 4.0) Loop.

The difference is that with the C# for statement, the loop is run from a single thread. However the Parallel class uses multiple threads. Moreover the order of the iteration in the parallel version is not necessarily in order.

Let us see an example:
1) Add one web page with Name "ParallelForVSFor"
2) Add two label controls on the page "ParallelForVSFor.aspx" file

<form id="form1" runat="server">
<table width="100%">
<td><asp:Label ID="parallelfor" runat="server" Text=""></asp:Label></td>
<td><asp:Label ID="csharpfor" runat="server" Text=""></asp:Label></td>

3) Add the following code in "ParallelForVSFor.aspx.cs" file
using System;
using System.Threading;
using System.Threading.Tasks;

protected void Page_Load(object sender, EventArgs e)
protected void Page_Load(object sender, EventArgs e)
parallelfor.Text += "Using Parallel.For \n";
Parallel.For(0,10,i =>
parallelfor.Text += "i="+i.ToString()+"\n";

csharpfor.Text += "Using C# For Loop \n";
for (int i = 0; i < 10; i++)
csharpfor.Text += "i=" + i.ToString() + "\n";

As you can see, the Parallel.For method is defined as Parallel.For Method (Int32, Int32, Action(Of Int32)). Here the first param is the start index (inclusive), the second param is the end index (exclusive) and the third param is the Action delegate that is invoked once per iteration. Here’s the output of running the code:

Using Parallel.For i=0 i=5 i=1 i=6 i=2 i=7 i=3 i=8 i=4 i=9
Using C# For Loop i=0 i=1 i=2 i=3 i=4 i=5 i=6 i=7 i=8 i=9

As you can see, with the C# for loop statement, the results are printed sequentially and the loop is run from a single thread. However with the Parallel.For method uses multiple threads and the order of the iteration is not in order.

The Parallel.For() construct is useful if you have a set of data that is to be processed independently. The construct splits the task over multiple processor.

No comments: