Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
635 views
in Technique[技术] by (71.8m points)

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

Why doesn't this break statement work? 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.

I have tried:

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

Neither stop the loop before the 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.");
            }
        });
    });
}

enter image description here

question from:https://stackoverflow.com/questions/65924213/how-to-break-out-of-an-inner-nested-parallel-foreach-loop-in-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The direct answer to your question is: curry the outer loop state and break it as you wish:

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...