Break parallel.foreach?
LoopState is certainly a great answer. I found the previous answers had so much other stuff that it was hard to see the answer, so here is a simple case:
using System.Threading.Tasks;
Parallel.ForEach(SomeTable.Rows(), (row, loopState) =>
{
if (row.Value == testValue)
{
loopState.Stop(); // Stop the ForEach!
}
// else do some other stuff here.
});
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.