I have the following code:
string[] arr = ["A", "B", "B", "B", "B", "B", "C"];
var options = new ParallelOptions() {
MaxDegreeOfParallelism = 3
};
Parallel.ForEach(arr, options , res =>
{
// No double res with the same name is allowed
// Code with res
});
I want the code in the parallel loop to be able to execute A and B at the same time and wait for the first B to finish in order to move to the next B.
In other word, it is not allowed to run the code on the same res at the same time.
With named semaphore, if I want to create a semaphore at runtime, it can't be static.
How can I resolve this issue?
Thanks
You can do this by grouping the items, and then run the
Parallel.ForEach()on the groups.Code (in which I added suffixes to the
Bs so we can distinguish them):Working Fiddle: https://dotnetfiddle.net/t5wm1a
Output run 1:
Output run 2:
The output shows:
Bstarts until the previousBhas ended.AandCrun in parallel with all of theBs.Update: initially I used
Task.DelaybutThread.Sleepis better in this scenario (see comments below).