C#:睡觉一个线程阻止他人?

时间:2011-11-29 01:21:26

标签: c# multithreading

我在C#,.NET 4.0和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);
    }
}

该代码的输出类似于:

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

如您所见,该程序每秒运行9,10个线程组(大约)。我不明白为什么会这样。我已经理解阻塞线程不应该影响其他人的执行。因此问题不应该是对Thread.Sleep的调用。

但是,如果我删除'Thread.Sleep(1000)'行,我会得到以下输出:

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

这个输出就像我预期的那样

有任何解释吗?

谢谢, 此致

2 个答案:

答案 0 :(得分:3)

任务并行库不会立即启动线程。它将在现有线程上安排执行或根据CPU数创建新线程。因此,它看起来像在您的计算机上任务并行库将使用10个线程并安排您的任务使用这些线程。

答案 1 :(得分:0)

你正在为每个线程单独休眠。