Breaking parallel loops in .NET C# using the Stop method

It’s not uncommon to break the execution of a for/foreach loop using the ‘break’ keyword. A for loop can look through a list of integers and if the loop body finds some matching value then the loop can be exited. It’s another discussion that ‘while’ and ‘do until’ loops might be a better alternative, but there you go.

You cannot simply break out from a parallel loop using the break keyword. However, we can achieve this effect with the ParallelLoopState class. Let’s say we have the following integer array…:

List<int> integers = new List<int>() { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

…and we want to break the loop as soon as we’ve found a number higher than 5. Both Parallel.For() and Parallel.ForEach() accepts an Action of T parameter as we saw before. This Action object has an overloaded version: Action of T and ParallelLoopState. The loop state is created automatically by the Parallel class. The loop state object has a Stop() method which stops the loop execution. Or more specifically it requests the loop to be stopped and the task scheduler will go about doing that. Keep in mind that some iterations may be continued even after the call to Stop was made:

Parallel.ForEach(integers, (int item, ParallelLoopState state) =>
{
	if (item > 5)
	{
		Console.WriteLine("Higher than 5: {0}, exiting loop.", item);
		state.Stop();
	}
	else
	{
		Console.WriteLine("Less than 5: {0}", item);
	}
});

So parallel loops can be exited but not with the same precision as in the case of synchronous loops.

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: