Parallel for loops in .NET C#

It’s trivial to start parallel loops in .NET using the built-in Parallel class. The class has a For() method with a wide variety of overloads. One of the easier ones accepts 3 parameters:

  • The start index: this is inclusive, i.e. this will be the first index value in the loop
  • The end index: this is exclusive, so it won’t be processed in the loop
  • An Action of int which represents the method that should be executed in each loop, where int is the actual index value

Example:

Parallel.For(0, 10, index =>
{
	Console.WriteLine("Task Id {0} processing index: {1}",
		Task.CurrentId, index);
});

If you run this code then you’ll see that the index values are indeed processed in a parallel fashion. The printout on the console windows may show that index 5 is processed a bit before 4 or that thread id 1 processed index 2 and thread #2 processed index 7. This all depends on the task scheduler so use parallel loops only in case you don’t care about the actual processing order.

View the list of posts on the Task Parallel Library here.

Unknown's avatarAbout Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

One Response to Parallel for loops in .NET C#

  1. Steven's avatar Steven says:

    Nice example for “Parallel for loop”.

Leave a comment

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

ARCHIVED: Bite-size insight on Cyber Security for the not too technical.