如何在 .NET 中创建固定大小的线程池?
我想在 .NET 中创建一个固定的任意大小的线程池 - 我知道默认大小是 25 - 但我希望有不同的大小,例如 5 或 10。有人吗?
I want to create a fixed arbitrary size ThreadPool in .NET - I understand the default size is 25 - but I wish to have a different size e.g. 5 or 10. Anyone?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
更改线程池的大小时应该小心。只有一个固定的系统线程池,供各种事物使用。将其设置得太小可能会导致您甚至认为自己没有使用过的区域出现问题。
如果您希望为一项特定任务使用相对较小的线程池,则应该使用单独的池。有各种可用的第三方池 - 我有一个相当旧的池作为 MiscUtil 的一部分,但是对于简单的用例来说它应该足够好了。我相信如果你看的话,你可以找到更高级的。
不幸的是,框架中还没有可实例化的
ThreadPool
。我不记得并行扩展是否会有效地提供一个,但我不认为它会。You should be careful about changing the size of the thread pool. There is just one fixed system thread pool, used by all kinds of things. Making it too small could cause problems in areas you didn't even think you were using.
If you want to have a relatively small thread pool for one specific task, you should use a separate pool. There are various third party pools available - I have a rather old one as part of MiscUtil, but it should be good enough for simple use cases. I'm sure you can find more advanced ones if you look.
It's unfortunate that there isn't an instantiable
ThreadPool
in the framework yet. I can't remember offhand whether Parallel Extensions will effectively provide one, but I don't think it will.您可以使用 ThreadPool.SetMinThreads 和 ThreadPool.SetMaxThreads 对线程数进行一些控制线程池中的线程。
话虽这么说,我建议谨慎使用它。您很容易陷入麻烦,因为 BCL 中的许多操作都依赖于可用的线程池线程。
You can use ThreadPool.SetMinThreads and ThreadPool.SetMaxThreads to have some control over the number of threads in the thread pool.
That being said, I recommend being cautious in using this. It's easy to get yourself into trouble, as many operations in the BCL rely on threadpool threads being available.
ThreadPool.SetMaxThreads(5,5) 然后任何超过五个线程都将排队。
ThreadPool.SetMaxThreads(5,5) and then anything over five threads will get queued.
您需要 ThreadPool.SetMaxThreads() 方法。
You want the ThreadPool.SetMaxThreads() method.