gpt4 book ai didi

c# - 为什么 Parallel.ForEach 不运行多个线程?

转载 作者:IT王子 更新时间:2023-10-29 04:31:23 26 4
gpt4 key购买 nike

今天我尝试对 foreach 语句进行一些优化,它适用于 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 大。

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

最佳答案

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

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.

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.

关于c# - 为什么 Parallel.ForEach 不运行多个线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8923230/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com