Break parallel.foreach? Break parallel.foreach? multithreading multithreading

Break parallel.foreach?


Use the ParallelLoopState.Break method:

 Parallel.ForEach(list,    (i, state) =>    {       state.Break();    });

Or in your case:

Parallel.ForEach<ColorIndexHolder>(ColorIndex.AsEnumerable(),    new Action<ColorIndexHolder, ParallelLoopState>((ColorIndexHolder Element, ParallelLoopState state) =>    {        if (Element.StartIndex <= I && Element.StartIndex + Element.Length >= I)        {            Found = true;            state.Break();        }    }));


You do this by calling using the overload of Parallel.For or Parallel.ForEach which passes in a loop state, then calling ParallelLoopState.Break or ParallelLoopState.Stop. The main difference is in how quickly things break - with Break(), the loop will process all items with an earlier "index" than the current. With Stop(), it will exit as quickly as possible.

For details, see How to: Stop or Break from a Parallel.For Loop.


What you should be using is Any, rather than a foreach loop:

bool Found = ColorIndex.AsEnumerable().AsParallel()    .Any(Element => Element.StartIndex <= I       && Element.StartIndex + Element.Length >= I);

Any is smart enough to stop as soon as it knows that the result must be true.