OdeToCode IC Logo

ParallelLoopState and Parallel.ForEach

Monday, October 10, 2011

The Task Parallel Library is a joy to work with – it's easy to use and thorough. Recently I was using Parallel.ForEach to process a large collection, but wanted to stop processing early, across all threads, if an individual item met specific criteria. It's as easy as adding a ParallelLoopState parameter to the action body.

var result = Parallel.ForEach(messages, (message, loopState) =>
{                
    if (message.IsOneThatStopsProcessing)
    {
        loopState.Stop();
    }

    // ...
    // other processing
    // ...

    outputStack.Push(message);
});

You can halt processing early by calling either Break or Stop on the loop state parameter. Break is for ordered collection where you want to halt at a specific location.