Break parallel.foreach?

前端 未结 5 617
醉酒成梦
醉酒成梦 2020-11-30 00:25

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

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

Parallel.ForEach

        
相关标签:
5条回答
  • 2020-11-30 00:36

    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();
            }
        }));
    
    0 讨论(0)
  • 2020-11-30 00:47

    Just use the loopState that can be provided.

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

    Look at this MSDN article for an example.

    0 讨论(0)
  • 2020-11-30 00:55

    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.
    });
    
    0 讨论(0)
  • 2020-11-30 00:57

    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.

    0 讨论(0)
  • 2020-11-30 01:00

    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.

    0 讨论(0)
提交回复
热议问题