Florian Florian - 16 days ago 9
C# Question

Is it possible to execute a Parallel.For loop starting max value, then decrementing

is it possible to parallelize a for loop starting the max value, then decrement ? In the Parallel.For signature, it seems to be only the case when "i" increments

for (int i = Int32.MaxValue; i >= 0; --i)
{
// do something...
}


Regards,

Florian

Answer

It should not matter if you are writing parallel code:

MSFT does not guarantee that the loop will run from low to high, or in any particular order.

Note: The Parallel.For method does not guarantee any particular order of execution. Unlike a sequential loop, some higher-valued indices may be processed before some lower-valued indices.

In practice, Parallel.For absolutely does not run in order.

Consider Jeppe Stig Nielsen's example (from comments):

System.Threading.Tasks.Parallel.For(0, 25, i => { Console.WriteLine(i); });

On my machine with 4 cores, I got the following output:

0
1
2
4
5
7
8
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
3
9
6

Clearly the loop is not in order.