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.

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.