gpt4 book ai didi

c# - WithDegreeOfParallelism(N>CPU 计数)

转载 作者:行者123 更新时间:2023-12-02 04:46:56 25 4
gpt4 key购买 nike

System.Threading.ThreadPool.SetMaxThreads(50, 50);
File.ReadLines().AsParallel().WithDegreeOfParallelism(100).ForAll((s)->{
/*
some code which is waiting external API call
and do not utilize CPU
*/
});

在我的系统中,线程数从未超过 CPU 数。我可以使用 PLINQ 并为每个 CPU 获得一个以上的线程吗?

最佳答案

如果您正在调用外部 Web API,您可能会达到并发连接数的限制,该限制设置为 2。在您的应用程序开始时执行以下操作:

System.Net.ServicePointManager.DefaultConnectionLimit = 4096;
System.Net.ServicePointManager.Expect100Continue = false;

尝试一下是否有帮助。否则,您尝试并行化的例程中可能存在其他瓶颈。

此外,正如其他响应者所说,ThreadPool 根据负载决定启动多少个线程。根据我使用 TPL 的经验,我发现线程数量会随着时间的推移而增加:应用程序运行时间越长,负载越重,就会启动更多线程。

关于c# - WithDegreeOfParallelism(N>CPU 计数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19638473/

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