Parallel.For Method in .NET 4.0 vs the C# For Loop

Posted by: Suprotim Agarwal , on 11/17/2010, in Category .NET Framework
Views: 214472
Abstract: In this article, we will explore the static method Parallel.For. A lot of developers ask me about the difference between the C# for loop statement and the Parallel.For. We will see the difference with an example

A couple of months ago, I had written some articles on the Parallel class found in the System.Threading.Tasks namespace which provides library-based data parallel replacements for common operations such as for loops, for each loops, and execution of a set of statements. You can read the articles here

Parallel Tasks in .NET 4.0

Parallel Tasks – Methods that Return value

Cancelling Tasks in .NET 4.0

In this article, we will explore the static method Parallel.For. A lot of developers ask me about the difference between the C# for loop statement and the Parallel.For. 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:

using System;
using System.Threading;
using System.Threading.Tasks;
 
namespace ParallelFor
{
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Using C# For Loop \n");
 
        for(int i=0; i <=10; i++){
            Console.WriteLine("i = {0}, thread = {1}",
                i, Thread.CurrentThread.ManagedThreadId);
            Thread.Sleep(10);
        }
 
        Console.WriteLine("\nUsing Parallel.For \n");
 
        Parallel.For(0, 10, i =>
        {
            Console.WriteLine("i = {0}, thread = {1}", i,
            Thread.CurrentThread.ManagedThreadId);
            Thread.Sleep(10);
        });
           
        Console.ReadLine();
    }
}

}


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<int> delegate that is invoked once per iteration. Here’s the output of running the code:

Parallel.For Loop 

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.

The entire source code of this article can be downloaded over here

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for Sixteen consecutive years. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Ehsan on Wednesday, November 17, 2010 12:33 PM
Nicely explained.
Comment posted by Gigimoi on Sunday, March 18, 2012 1:39 AM
No performance testing?
Comment posted by Diego on Friday, July 27, 2012 1:47 PM
I had done a little and simple performance testing and was found that the Parallel.For is better than classic for loop and is faster 50 more or less in a quad core environment%
Comment posted by Piotr on Sunday, May 26, 2013 5:36 PM
Pity that the example is quite impractical. Perhaps, you would like to expand the topic in the future. The use can be understood by the name "parallel for" by itself, but the trick is when to use it. Sorry for being so critical.
Comment posted by Captain on Friday, August 2, 2013 1:40 AM
If we use the stopwatch and measure the excution time then Parallel For loop and Parallel ForEach loops are faster.
Please have look at tese links. The time execution time is measured in both the for and parallel for loop. You will come to know the difference instantly.

http://www.dotnetlines.com/Blogs/tabid/85/EntryId/28/Parallel-For-loop-in-Net-4-0.aspx

http://www.dotnetlines.com/Blogs/tabid/85/EntryId/29/Parallel-ForEach-loop-in-Net-4-0.aspx