Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How do I add a finalizer that runs once all parallels have completed?

Parallel.ForEach(entries, new ParallelOptions { MaxDegreeOfParallelism = 15 }, async (entry) =>
    // Do something with the entry.
});

I have tried like this but it doesn't compile:

Parallel.ForEach(entries, new ParallelOptions { MaxDegreeOfParallelism = 15 }, async (entry) =>
    // Do something with the entry.
}, () => { // Was hoping this would work. });
See Question&Answers more detail:os

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

1 Answer

  1. You should not declare the action for the Parallel.ForEach as async. If you use an await inside that action, the control flow is returned to Parallel.ForEach and its implementation "thinks" that the action is finished. This will lead to a very different behaviour than you expect.

  2. The call to Parallel.ForEach returns when the loop is completed. It returns when all actions have been done for all the elements in the enumeration. So whatever you want to do "when all parallels have completed" can be done right after that call:

    Parallel.ForEach(entries, new ParallelOptions { MaxDegreeOfParallelism = 15 }, 
             (entry) =>
             // Do something with the entry.
    );
    DoSomethingWhenAllParallelsHaveCompleted();
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...