简体   繁体   English

如何突破 C# 中的内部嵌套 Parallel.Foreach 循环?

[英]How to break out of an inner nested Parallel.Foreach loop in C#?

Why doesn't this break statement work?为什么这个 break 语句不起作用? My goal is to break out of the inner loop only , but keep processing the outer loop.我的目标是只跳出内循环,但继续处理外循环。 It is hitting the Console.WriteLine() no matter what I do.无论我做什么,它都会触发Console.WriteLine()

I have tried:我试过了:

  1. innerLoopState.Break()
  2. innerLoopState.Stop()

Neither stop the loop before the Console.WriteLine() ...Console.WriteLine()之前都不会停止循环 ...

private static ParallelOptions ParallelCityOptions => new ParallelOptions
{
    MaxDegreeOfParallelism = 2
};

private static ParallelOptions ParallelPeopleOptions => new ParallelOptions
{
    MaxDegreeOfParallelism = 3
}

[Test]
public void NestedParallelForeach()
{
    var listOfCities = new List<string> {"Atlanta", "Denver", "Scranton",};
    var listOfPeople = new List<string>() {"Bob", "Sally", "Craig", "Bill"};

    Parallel.ForEach(listOfCities, ParallelCityOptions, city =>
    {
        Parallel.ForEach(listOfPeople, ParallelPeopleOptions, (person, innerLoopState) =>
        {

            if (person == "Bill")
            {
                // do something
                innerLoopState.Break();
                Console.WriteLine("Should never hit this line.");
            }
        });
    });
}

在此处输入图像描述

The direct answer to your question is: curry the outer loop state and break it as you wish:对你的问题的直接回答是:咖喱外循环 state 并按你的意愿打破它:

Parallel.ForEach(listOfCities, ParallelCityOptions, (city, outerLoopState) =>
{
    Parallel.ForEach(listOfPeople, ParallelPeopleOptions, (person, innerLoopState) =>
    {

        if (person == "Bill")
        {
            // do something
            outerLoopState.Break();
            innerLoopState.Break();
            Console.WriteLine("Should never hit this line.");
        }
    });
});

However all of the elements in your array will be processed by your code at once, since there's so few compared to the number of cores a modern computer has.但是,您的数组中的所有元素都将由您的代码立即处理,因为与现代计算机的内核数量相比,它们太少了。 Simply requesting a parallel loop break won't magically break all threads, it will just stop new ones from being processed.简单地请求并行循环中断不会神奇地中断所有线程,它只会阻止处理新线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM