user7114146
user7114146

Reputation:

C# Parallel for loop

I don't think I understand the Parallel for loop.. when I try this program

    Parallel.For(1, 20, i =>
    {
        Thread.Sleep(200);
        Console.WriteLine(i);
    }); 

it will spit out:

1
10
19
2
11
4
3
12
5
6
13
17
7
14
18
8
15
9
16

what I'm wanting to do is have a for loop threaded with a limit of 20 threads and make it print out like this, 1,2,3,4,5,6,7,8,9,10.. ect

Upvotes: 0

Views: 503

Answers (1)

Luaan
Luaan

Reputation: 63772

When you run a loop in parallel, you no longer have any guarantees on the ordering of the results. That's pretty much multi-threading 101 :)

If you need guaranteed ordering, avoid side-effects and order the results.

Upvotes: 3

Related Questions