Reputation: 667
I have the next code in C#, .NET 4.0 and Windows 7
class Program
{
static void Main(string[] args) {
DateTime startTime = DateTime.Now;
Parallel.For(1, 100, ind => {
System.Console.WriteLine("IND => " + ind + "; DEMORA: " + (DateTime.Now - startTime).TotalMilliseconds);
Thread.Sleep(1000);
});
Console.Write("\nPresione una tecla para finalizar...");
Console.ReadKey(true);
}
}
The output of that code is similar to this:
IND => 8; DEMORA: 6001,9531
IND => 31; DEMORA: 6002,9297
IND => 55; DEMORA: 6006,8359
IND => 12; DEMORA: 6008,789
IND => 80; DEMORA: 6009,7656
IND => 57; DEMORA: 6009,7656
IND => 79; DEMORA: 6010,7422
IND => 34; DEMORA: 6011,7187
IND => 16; DEMORA: 6010,7422
IND => 19; DEMORA: 7001,9531
IND => 35; DEMORA: 7002,9297
IND => 59; DEMORA: 7006,8359
IND => 43; DEMORA: 7008,789
IND => 81; DEMORA: 7009,7656
IND => 58; DEMORA: 7010,7422
IND => 67; DEMORA: 7011,7187
IND => 83; DEMORA: 7011,7187
IND => 17; DEMORA: 7012,6953
IND => 20; DEMORA: 8001,9531
IND => 36; DEMORA: 8002,9297
IND => 60; DEMORA: 8006,8359
IND => 44; DEMORA: 8008,789
IND => 82; DEMORA: 8009,7656
IND => 71; DEMORA: 8009,7656
IND => 72; DEMORA: 8010,7422
IND => 68; DEMORA: 8011,7187
IND => 84; DEMORA: 8011,7187
IND => 18; DEMORA: 8012,6953
As you can see, the program runs groups of 9,10 threads per second (approximately). I can not understand why is this. I have understood that blocking a thread should not affect the execution of others. Therefore the problem should not be the call to Thread.Sleep.
But, if I delete the line 'Thread.Sleep(1000)' I get the following output:
IND => 78; DEMORA: 20,5078
IND => 79; DEMORA: 21,4844
IND => 69; DEMORA: 18,5547
IND => 53; DEMORA: 19,5312
IND => 97; DEMORA: 20,5078
IND => 80; DEMORA: 24,414
IND => 9; DEMORA: 13,6719
IND => 70; DEMORA: 26,3672
IND => 10; DEMORA: 29,2969
IND => 11; DEMORA: 29,2969
IND => 12; DEMORA: 30,2734
IND => 13; DEMORA: 30,2734
IND => 14; DEMORA: 31,25
IND => 15; DEMORA: 32,2265
IND => 71; DEMORA: 29,2969
IND => 72; DEMORA: 32,2265
This output is like I expected
Any explanation?
Thanks, Regards
Upvotes: 0
Views: 356
Reputation: 1221
The Task Parallel Library will not start threads immediately. It will schedule execution on existing threads or create new threads based on number of CPUs. Therefore it looks like on your computer Task Parallel Library will use 10 threads and schedule your tasks to use these threads.
Upvotes: 3