Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to define the execution order in Parallel.For?

// parameters.Count == 10
// actualFreeLicenses == 2
Parallel.For(0, parameters.Count, new ParallelOptions() 
                    {
                        MaxDegreeOfParallelism = actualFreeLicenses
                    }, i =>
                    {
                        ExternalProgram(i);
                    }
);

When I execute the above code I notice that the value of i passed to the ExternalProgram method are 1 & 6, later 2 & 7, later 3 & 8 ...

If I have 14 Parameters and 2 licenses it always launch 1 & 8, later 2 & 9 ...

Is it possible to define order: first 1 & 2, later 3 & 4 etc?

like image 535
Saint Avatar asked Sep 29 '11 09:09

Saint


2 Answers

How about using a Queue/ConcurrentQueue and dequeueing items in the body of your parallel loop? This will ensure that ordering is preserved.

like image 74
spender Avatar answered Oct 04 '22 20:10

spender


If you are using Parallel the order in which they are executed is not of relevance therefore "Parallel". You should use a sequential workflow if the order is relevant for you.

like image 26
oberfreak Avatar answered Oct 04 '22 18:10

oberfreak