Breaking out of Parallel.ForEach

Parallel.ForEach is a great way to easily distribute work across multiple threads. But what if you want to cancel the execution before you’ve finished the work? Sure, you can use a Cancellation Token, but that seems messy and complicated.

A simpler way to do this is with ParallelLoopState.

1
2
3
4
5
6
7
8
9
10
11
var itemCollection = getItemsToProcess();

Parallel.ForEach(itemCollection,
(item, loopstate) =>
{
processItem(item);
if (shouldStop()) {
loopstate.Stop();
}
}
);

That’s it!

You can also use this with Parallel.For

1
2
3
4
5
6
7
8
9
10
11
var itemCollection = getItemsToProcess();

Parallel.For(0, itemCollection.length,
(i, loopstate) =>
{
processItem(itemCollection[i]);
if (shouldStop()) {
loopstate.Stop();
}
}
);