当没有更多可用线程时 .ForEach 循环是否阻塞
我们有一个 .ForEach
循环 (TPL),它启动很多很多任务。 由于 TPL 正在消耗线程池中的线程,我想知道当没有更多可用线程时会发生什么? 调用代码会阻塞直到线程再次可用吗?
我知道线程池有一个全局工作队列,工作项(Task
)将在其中排队。队列会满吗?
我们的问题是,有些任务运行时间较长(30 分钟),有些任务运行时间较短(一秒),但我们有数千个这样的任务,甚至更多。 TPL 是否为我启动的每个任务启动一个新线程?我认为不是。线程池什么时候会耗尽?
We have a .ForEach
loop (TPL) which starts many, many, many Tasks.
Since the TPL is consuming threads from the thread pool I am wondering what will happen when there are no more threads available?
Will the calling code block until threads are available again?
I know the threadpool has a global work queue where work items (Task
) will be queued. Can that queue ever be full?
Our problem is that some of the tasks are long running (30 minutes) and some are short (a second), but we have thousands of such Tasks, if not more. Does the TPL start a new Thread for each Task I start? I think not. At what point will the thread pool be exhausted?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当没有更多的空闲线程时,会启动多种算法。主要的一个是线程池将慢慢创建额外的线程(最多 2 个/秒)。
这有助于解决长时间运行任务的情况,但系统并不完美。请注意创建数百个线程的情况,您的应用程序可能会崩溃。
第一种方法是在 ForEach 上指定 DegreeOfParallelism。您希望将线程数限制为
numberOfCores * someFactor
,其中 someFactor 取决于任务执行的 I/O。您还可以研究自定义 TPL 调度程序,我对此了解不多。
When there are no more free Threads there are several algorithms kicking in. Yhe main one is that the ThreadPool will slowly create extra threads (max 2/second).
This helps to address your situation with long-running tasks, but the system is not perfect. Be ware of a situation where hundreds of threads are created, your app will probably crash.
First approach would be to specify a DegreeOfParallelism on the ForEach. You want to limit the number of threads to
numberOfCores * someFactor
where someFactor depends on the I/O the Tasks perform.You could also investigate custom TPL schedulers, I don't know much about that.