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:

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

HarsH ReaLiTy

A Good Blog is Hard to Find

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 TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

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: