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


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.


About 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 says:

    Nice example for “Parallel for loop”.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog


Once Upon a Camayoc

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

%d bloggers like this: