0

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

9
  • 2
    this is what it happens in a multithreaded environment. The threads are not running in the order you expect them to do. The solution is not to expect them to run in that order, or do not use a parallel for Commented Nov 4, 2016 at 9:44
  • So you want parallelism, but you want every operation to wait on the previous one? Commented Nov 4, 2016 at 9:44
  • @meJustAndrew got any suggestions on how I accomplish do my task? Commented Nov 4, 2016 at 9:45
  • @CodeCaster I want the loop to run on their own thread Commented Nov 4, 2016 at 9:45
  • Parallel.For will create as many threads as is optimal for the computer running the code (e.g. 8 threads for a quad-core hyperthreaded CPU, but only 1 thread for a simple ARM device), you cannot set an absolute number of threads, but you can place a limit with the MaxDegreeOfParallelism option. Commented Nov 4, 2016 at 9:46

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.