Break parallel.foreach?

Rasmus Søborg picture Rasmus Søborg · Sep 24, 2012 · Viewed 53.7k times · Source

How do I break out of an parallel.for loop?

I have a pretty complex statement which looks like the following:

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

Using parallel class, I can optimize this process by far. However; I cannot figure out how to break the parallel loop? The break; statement throws following syntax error:

No enclosing loops out of which to break or continue

Answer

Tudor picture Tudor · Sep 24, 2012

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();
        }
    }));