There is such a simple snippet:

System.Threading.Tasks.Parallel.For(0, 30, p => { System.Threading.Thread.Sleep(p*500); Console.WriteLine(Convert.ToString(p)); }); 

According to the logic at the exit, we should see the sequence: 0,1,2,3 ... 28,29 And the script itself should take 15 seconds. But at the output we get a sequence of these numbers mixed. What's wrong? how to do?

  • it works in multithreading, as you wanted, the result even says so - Yaroslav

1 answer 1

Why sequence? The essence of multithreading lies in the fact that threads run in parallel , that is, simultaneously . Accordingly, each stream displays its data, which is mixed with data from another stream.

Why 15 seconds? First, the launch of the stream takes time (how much - it is impossible to predict). Even if a ready stream is taken from the pool, then the time will be different (there may not be free streams, you will have to wait for their release). In addition, systems with different number of cores will use a different number of threads.

About 15 seconds will turn out only on a single-core / single-threaded system, if you set the sleep time of the thread to 500 milliseconds: Thread.Sleep(500) . And you have there p*500 .


If you need the sequence 0,1,2,3 ... 28,29, run your code in one thread.


It seems I understood how you imagined the execution of the code: 30 threads will start at the same time , everyone will sleep for a certain amount of time, then they will print the result. A kind of comic sleep sorting - Sleep Sort .

But, as I said, the threads do not start at the same time; some interval from 0 to 30 will be transferred to execution in one thread.

And most importantly, calling Thread.Sleep does not guarantee that the thread will sleep exactly the specified time. It only means to instruct the system to wake up the flow after a specified period of time. And if at the moment there are other threads loaded with work, then it may take significantly longer to wake up.