Parallel for loops in .NET C#
April 9, 2014 1 Comment
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.
Nice example for “Parallel for loop”.