Quick question for people used to Parallel, I have the following piece of code, nothing fancy:
var result = Parallel.For(0, 10, (i) =>
{
Console.WriteLine(DateTime.Now.ToLongTimeString() + "Start sleep: " + i);
Thread.Sleep(i * 1000);
Console.WriteLine(DateTime.Now.ToLongTimeString() + "Done sleep: " + i);
});
Console.WriteLine("DONE!");
And I sort of expected it to take around 9 seconds, maybe a little more depending on the scheduler. But it took anywhere from 12 to 25+ seconds Can someone explain why?
Here's a sample output taking 20s and my comments. Why does the scheduler wait for such a long time before launching the last one? There was a lot of time to launch it. Also, sometimes it is done nicely and quickly (earlier)... why the huge variance? Not much changing on my side from run to run.
5:10:24 PMStart sleep: 5 --> 5
5:10:24 PMStart sleep: 0 --> 5 0
5:10:24 PMDone sleep: 0 --> 5
5:10:24 PMStart sleep: 1 --> 5 1
5:10:24 PMStart sleep: 3 --> 5 1 3
5:10:25 PMStart sleep: 6 --> 5 1 3 6
5:10:25 PMDone sleep: 1 --> 5 3 6
5:10:25 PMStart sleep: 2 --> 5 3 6 2
5:10:26 PMStart sleep: 4 --> 5 3 6 2 4
5:10:27 PMStart sleep: 7 --> 5 3 6 2 4 7
5:10:27 PMDone sleep: 2 --> 5 3 6 4 7
5:10:27 PMStart sleep: 8 --> 5 3 6 4 7 8
5:10:27 PMDone sleep: 3 --> 5 6 4 7 8
5:10:29 PMDone sleep: 5 --> 6 4 7 8
5:10:30 PMDone sleep: 4 --> 6 7 8
5:10:31 PMDone sleep: 6 --> 7 8
5:10:34 PMDone sleep: 7 --> 8
5:10:35 PMDone sleep: 8 --> EMPTY
5:10:35 PMStart sleep: 9 --> 9
5:10:44 PMDone sleep: 9 --> EMPTY
DONE!