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.

Advertisements

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:

WordPress.com Logo

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

Google+ photo

You are commenting using your Google+ 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

ultimatemindsettoday

A great WordPress.com site

Elliot Balynn's Blog

A directory of wonderful thoughts

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT BEST PRACTICES WITH MICROSOFT STACK & ANGULAR

Cyber Matters

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

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: