Parallel stepped for loops in .NET C#

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.

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

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.