Parallel.ForEach比预期花费更多时间

时间:2012-04-27 04:15:00

标签: c# .net multithreading parallel-processing threadpool

这里有关于这个问题的代码:

while (true)
{
    Console.WriteLine("start " + DateTime.Now);
    ParallelOptions options = new ParallelOptions();
    options.MaxDegreeOfParallelism = -1;                
    Parallel.ForEach(hosts, item =>
    {
        using (Ping ping = new Ping())
        {
            PingReply pingReply = ping.Send(item.Value, 2000);  // timeout is 2 secs
            App.dict[item.Key].lastConnectTry = new KeyValuePair<bool, DateTime>((pingReply.Status == IPStatus.Success), DateTime.Now);
        }
    });        
    Console.WriteLine("end " + DateTime.Now);
    Thread.Sleep(15000);
}

但是,然后我运行该应用程序会产生稍微不同的结果:

start 27.04.2012 10:12:32
end 27.04.2012 10:12:42
// it took 10 seconds
start 27.04.2012 10:12:57
end 27.04.2012 10:13:02
// this took 5 secs
start 27.04.2012 10:13:17
end 27.04.2012 10:13:22
//   5 secs
start 27.04.2012 10:13:37
end 27.04.2012 10:13:42
// 5 secs
start 27.04.2012 10:13:57
end 27.04.2012 10:14:01
start 27.04.2012 10:14:16
end 27.04.2012 10:14:19
start 27.04.2012 10:14:34
end 27.04.2012 10:14:36
start 27.04.2012 10:14:51
end 27.04.2012 10:14:54
start 27.04.2012 10:15:09
end 27.04.2012 10:15:11
start 27.04.2012 10:15:26
end 27.04.2012 10:15:29
start 27.04.2012 10:15:44
end 27.04.2012 10:15:46
start 27.04.2012 10:16:01
end 27.04.2012 10:16:06
start 27.04.2012 10:16:21
end 27.04.2012 10:16:24
start 27.04.2012 10:16:39
end 27.04.2012 10:16:41
start 27.04.2012 10:16:56
end 27.04.2012 10:16:59
start 27.04.2012 10:17:14
end 27.04.2012 10:17:16

似乎需要一些时间来引导线程,创建它们然后并行执行时间将正确安排。

所以问题是为什么处理所有处理所需的时间超过2秒,如何通过在处理之前引导线程来避免它?

更新

此循环放在单独的后台线程中。

2 个答案:

答案 0 :(得分:2)

是的,threadpool需要根据负载增加线程数(与Parallel.ForEach无关)。

检查Parallel.ForEach not spinning up new threadsParallel.Foreach spawning way too many threads是否有背景。

答案 1 :(得分:1)

您实际上没有通过并行选项,请参阅此处:

ParallelOptions options = new ParallelOptions();
options.MaxDegreeOfParallelism = -1;                
Parallel.ForEach(hosts, options, item => // note options passed through here
      // etc

如果创建不够,可以增加threadpool:

System.Threading.ThreadPool.SetMinThreads System.Threading.ThreadPool.SetMaxThreads

但请注意,除非你知道你会得到改进,否则我不会碰这个。由于您在任务代码中执行Ping,这可能会增加每次运行之间的可变性。