c# - 打破 parallel.foreach?

标签 c# multithreading parallel-processing 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;
        }
    }));

使用并行类,我可以优化这个过程。然而;我不知道如何打破并行循环? break; 语句抛出以下语法错误:

No enclosing loops out of which to break or continue

最佳答案

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

关于c# - 打破 parallel.foreach?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12571048/

相关文章:

C# 单管道语法

c# - 如何将c#中的列表转换为javascript中的数组并检查数组项

创建新流程并期待输出

c++ - 无法重定向程序的控制台输出

使用有限线程的 Java 并发

java - 这是 fork in join 的正确代码吗?

c# - 如何使用带有 MVVM 的 WPF 应用程序中的 FolderBrowserDialog

c# - Visual Studio : Debugging a referenced DLL, 我在另一个 SLN 中有源代码

linux - 如何通过为每个 Linux 内核启动一个任务来(简单地)与 Linux shell 并行化?

c# - 使用 Parallel.For 时 throttle