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

查看:17
本文介绍了为什么 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 只打开了一个线程!结果 Parallel 的时间跨度大于标准的 foreach.

I saw that .NET in Parallel.ForEach(...) opened ONLY one thread! As a result the timespan of Parallel was bigger than standard foreach.

为什么你认为 .NET 只打开了 1 个线程?因为锁定文件?谢谢

Why do you think .NET only opened 1 thread? Because of locking of file? Thanks

推荐答案

按照设计,Parallel.ForEach 可能使用比请求更少的线程来实现更好的性能.根据 MSDN [link]:

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天全站免登陆