Parallel.ForEach takes longer than expected

Here's the code for this:

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);
}

But then I launched this application, it gives slightly different results:

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

It seems like it takes some time to load the threads, creating them, and then the parallel execution time will be properly organized.

So, the question is why it takes more than 2 seconds to process all the processing, and how can I avoid this by loading threads before processing?

Update:

This loop is placed in a separate background thread.

+3
source share
2 answers

Yes, threadpool needs to increase the number of threads based on load (not related to Parallel.ForEach).

Parallel.ForEach, Parallel.Foreach, .

+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 , .

+1

All Articles