Parallel stepped for loops in .NET C#
April 15, 2014 Leave a comment
We saw in this post how to create a parallel for loop using the Parallel object in .NET. One drawback of that method is the we cannot create the parallel equivalent of a synchronous stepped for loop:
for (int i = 0; i < 20; i += 2)
Parallel.For accepts the start index and the end index but not the step value. Parallel.ForEach comes to the rescue: we create an integer list with only those values that should be processed. Create the stepped integer list as follows:
public IEnumerable<int> SteppedIntegerList(int startIndex,
int endEndex, int stepSize)
{
for (int i = startIndex; i < endEndex; i += stepSize)
{
yield return i;
}
}
Then call Parallel.ForEach:
Parallel.ForEach(SteppedIntegerList(0, 20, 2), index =>
{
Console.WriteLine("Index value: {0}", index);
});
View the list of posts on the Task Parallel Library here.