为什么不是Parallel.ForEach运行多个线程? [英] Why isn't Parallel.ForEach running multiple threads?

查看:313
本文介绍了为什么不是Parallel.ForEach运行多个线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天,我试着做了一些优化,以的foreach 语句,即在的XDocument

Today i tried do some optimization to foreach statement, that works on XDocument.

优化前:

foreach (XElement elem in xDoc.Descendants("APSEvent").ToList())
{
    //some operations
}

优化后:

Parallel.ForEach(xDoc.Descendants("APSEvent").ToList(), elem =>
{
    //same operations
});



我看到,在 Parallel.ForEach的.NET(...) 只打开一个线程!其结果是,并行的时间跨度比标准的foreach

I seen, that .NET in Parallel.ForEach(...) opens ONLY one thread!!! As a result, timespan of Parallel was bigger than standard foreach.

你认为,为什么.NET无法打开> 1线程?由于文件的锁呢?
谢谢

What do you think, why .NET can not open >1 threads? Because of locking of file? Thanks

推荐答案

这是由设计Parallel.ForEach可以使用较少的线程比要求获得更好的性能。根据MSDN [链接]

It's by design that Parallel.ForEach may use fewer threads than requested to achieve better performance. According to MSDN [link]:

默认情况下,Parallel.ForEach和方法的Parallel.For可以使用变量多项任务。这就是为什么,例如,ParallelOptions类有一个MaxDegreeOfParallelism属性,而不是一个MinDegreeOfParallelism属性。 的想法是,该系统可以使用较少的线程比请求来处理的循环。

By default, the Parallel.ForEach and Parallel.For methods can use a variable number of tasks. That's why, for example, the ParallelOptions class has a MaxDegreeOfParallelism property instead of a "MinDegreeOfParallelism" property. The idea is that the system can use fewer threads than requested to process a loop.

的.NET线程池动态地适应通过允许工作线程并行任务的数量随时间变化变化的工作负荷。的在运行时,系统观察是否增加线程的数量,从而提高或降低总吞吐量并相应地调整工作线程的数量。

The .NET thread pool adapts dynamically to changing workloads by allowing the number of worker threads for parallel tasks to change over time. At run time, the system observes whether increasing the number of threads improves or degrades overall throughput and adjusts the number of worker threads accordingly.

这篇关于为什么不是Parallel.ForEach运行多个线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆