打破parallel.foreach?

Ras*_*org 95 c# parallel-processing multithreading parallel.foreach

如何打破parallel.for循环?

我有一个非常复杂的声明,如下所示:

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

使用并行类,我可以到目前为止优化这个过程.然而; 我无法弄清楚如何打破并行循环?该break;语句抛出以下语法错误:

没有封闭的环可以打破或继续

Tud*_*dor 167

使用ParallelLoopState.Break方法:

 Parallel.ForEach(list,
    (i, state) =>
    {
       state.Break();
    });
Run Code Online (Sandbox Code Playgroud)

或者在你的情况下:

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();
        }
    }));
Run Code Online (Sandbox Code Playgroud)

  • @Hendrik Wiese:文档说:`调用Break方法通知操作,在当前的迭代之后不必执行迭代.但是,如果它们尚未执行,那么在当前迭代之前的所有迭代仍然必须执行.并且"不能保证当前迭代之后的迭代肯定不会执行." (3认同)
  • 那么`state.Stop()` 更适合可靠地实现预期结果,如下文 Mike Perrenoud 和 MBentley 所述 (2认同)

Ree*_*sey 39

你可以通过使用重载Parallel.ForParallel.ForEach调用循环状态调用,然后调用ParallelLoopState.Break或来执行此操作ParallelLoopState.Stop.主要区别在于事物的破坏速度 - Break()循环将使用比当前更早的"索引"处理所有项目.随着Stop(),它将尽快退出.

有关详细信息,请参见如何:从Parallel.For循环停止或中断.

  • +1,看起来我们这里的几个人有完全相同的答案:) - 哦,我在那个其他评论人那里得到你的支持. (3认同)

Ser*_*rvy 12

你应该使用的是Any,而不是foreach循环:

bool Found = ColorIndex.AsEnumerable().AsParallel()
    .Any(Element => Element.StartIndex <= I 
      && Element.StartIndex + Element.Length >= I);
Run Code Online (Sandbox Code Playgroud)

Any 一旦知道结果必须为真,就足够聪明地停下来.


MBe*_*ley 8

LoopState当然是一个很好的答案.我发现之前的答案有很多其他的东西,很难看到答案,所以这是一个简单的案例:

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.
});
Run Code Online (Sandbox Code Playgroud)


Mik*_*oud 5

只需使用loopState可提供的即可.

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

查看此MSDN文章以获取示例.