线程池最大线程数
我在 .NET 的 ThreadPool (.NET 4) 方面遇到了一些麻烦。
我读到,默认情况下 .NET 每个处理器的线程数限制为 25 个,但根据 SO 和其他地方的论坛帖子,我可以使用以下代码增加限制。
void SetThreads(int threads)
{
ThreadPool.SetMaxThreads(threads, threads);
ThreadPool.SetMinThreads(threads, threads);
}
但是,当我将上面的值设置为任意高的数字(例如 2000)和队列约 1000 个项目时,我仍然只有约 33 个线程在运行(.NET CLR 需要约 5 个线程),并且 ThreadPool.GetAvailableThreads( ) 返回剩余 1971 个线程。
为什么上面的代码不起作用?
I've got some trouble with .NET's ThreadPool (.NET 4).
I've read that by default .NET has a limit of 25 threads per processor, but according to forum posts on SO and on other places, I can increase the limit with the below code.
void SetThreads(int threads)
{
ThreadPool.SetMaxThreads(threads, threads);
ThreadPool.SetMinThreads(threads, threads);
}
However, when I set the above to some arbitrarily high number, for example, 2000, and queue ~1000 items, I still only have ~33 threads running (.NET CLR takes ~5 threads), and ThreadPool.GetAvailableThreads()
returns 1971 threads remaining.
Why doesn't the code above work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先,您对默认值的“了解”是不正确的。每个处理器 25 个线程的限制已从 .NET 1.1 中恢复。它在 .NET 2 中有所增加,现在:
然而,还有其他因素在起作用:线程池不会在所有情况下立即创建新线程。为了应对突发的小任务,它限制了创建新线程的速度。 IIRC,如果有未完成的任务,它将每0.5秒创建一个线程,直到最大线程数。不过,我无法立即看到记录的数字,因此它很可能会发生变化。我强烈怀疑这就是你所看到的。尝试对大量项目进行排队,然后监视一段时间内的线程数。
Firstly, your "knowledge" of the defaults is incorrect. The limit of 25 threads per processor was back from .NET 1.1. It was increased in .NET 2, and now:
However, there's something else at play: the thread pool doesn't immediately create new threads in all situations. In order to cope with bursts of small tasks, it limits how quickly it creates new threads. IIRC, it will create one thread every 0.5 seconds if there are outstanding tasks, up to the maximum number of threads. I can't immediately see that figure documented though, so it may well change. I strongly suspect that's what you're seeing though. Try queuing a lot of items and then monitor the number of threads over time.
来自 MSDN :
也请阅读此内容:并行编程模式:使用 .NET Framework 4 理解和应用并行模式
From the MSDN :
Read this too: Patterns for Parallel Programming: Understanding and Applying Parallel Patterns with the .NET Framework 4
首先查看这个链接,特别是这个备注:
然后您应该检查 ThreadPool.SetMaxThreads(threads,threads) 方法的返回值。也许它返回
false
?Firstly check this link, especially this remark:
Then you should check the return value of
ThreadPool.SetMaxThreads(threads, threads)
method. Maybe it returnsfalse
?