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
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)
Ree*_*sey 39
你可以通过使用重载Parallel.For或Parallel.ForEach调用循环状态调用,然后调用ParallelLoopState.Break或来执行此操作ParallelLoopState.Stop.主要区别在于事物的破坏速度 - Break()循环将使用比当前更早的"索引"处理所有项目.随着Stop(),它将尽快退出.
有关详细信息,请参见如何:从Parallel.For循环停止或中断.
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 一旦知道结果必须为真,就足够聪明地停下来.
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)
只需使用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文章以获取示例.
| 归档时间: |
|
| 查看次数: |
45190 次 |
| 最近记录: |