如何突破 循环?
我有一个非常复杂的语句,如下所示:
Parallel.ForEach<ColorIndexHolder>(ColorIndex.AsEnumerable(),
new Action<ColorIndexHolder>((ColorIndexHolder Element) =>
{
if (Element.StartIndex <= I && Element.StartIndex + Element.Length >= I)
{
Found = true;
break;
}
}));使用并行类,到目前为止我可以优化这个过程。但是,我想不出如何打破并行循环?break;语句抛出以下语法错误:
没有要中断或继续
的封闭循环
发布于 2012-09-25 02:56:39
使用ParallelLoopState.Break方法:
Parallel.ForEach(list,
(i, state) =>
{
state.Break();
});或者在你的例子中:
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();
}
}));发布于 2012-09-25 02:56:25
为此,您可以使用Parallel.For或Parallel.ForEach的重载(以循环状态传递)进行调用,然后调用ParallelLoopState.Break或ParallelLoopState.Stop。主要的区别在于事情中断的速度-使用Break(),循环将处理所有具有比当前索引更早的“索引”的项。有了Stop(),它将尽可能快地退出。
详情请参见How to: Stop or Break from a Parallel.For Loop。
发布于 2012-09-25 02:58:04
您应该使用Any,而不是foreach循环:
bool Found = ColorIndex.AsEnumerable().AsParallel()
.Any(Element => Element.StartIndex <= I
&& Element.StartIndex + Element.Length >= I);Any足够聪明,一旦它知道结果肯定是真的,它就会停止。
https://stackoverflow.com/questions/12571048
复制相似问题