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.

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

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: