简体   繁体   English

Task.Run(Action)是否启动新的线程ID,所以ThreadPool中没有更多线程了吗?

[英]Does Task.Run(Action) Start a new Thread id there are no more threads in the ThreadPool?

According to msdn , Task.Run(Action) uses a Thread in the ThreadPool to actually execute the Action, my question is (as the tile states), would Task.Run start a new Thread if there are none available in the ThreadPool? 根据msdn的说法,Task.Run(Action)在ThreadPool中使用线程来实际执行Action,我的问题是(作为平铺状态),如果ThreadPool中没有可用的Task.Run是否将启动一个新线程? Or would it just wait until there is one available? 还是只是等到有一种可用?

[tl;dr] I'm currently enqueuing a some calls directly to the ThreadPool: [tl; dr]我当前正在将一些调用直接排队到ThreadPool:

ThreadPool.QueueUserWorkItem(x => ...);

But, I've noticed that under some loads, the Application does run out of Threads in the pool (Parallel.ForEach being at fault, somewhere else in the program). 但是,我注意到在某些负载下,应用程序确实会耗尽池中的线程(Parallel.ForEach在程序的其他地方出错)。

I know that increasing the number of Threads in the Pool will probably NOT solve anything, so I'm thinking to use the MaxDegreeOfParallelism (ParallelOptions) to control the number of Threads used by Parallel.Foreach. 我知道增加池中的线程数可能无法解决任何问题,因此我在考虑使用MaxDegreeOfParallelism(ParallelOptions)来控制Parallel.Foreach使用的线程数。

Anyhow, I would still like to know the answer to the stated question. 无论如何,我仍然想知道上述问题的答案。

Thanks =] 谢谢=]

would Task.Run start a new Thread if there are none available in the ThreadPool? 如果ThreadPool中没有可用的Task.Run将启动一个新线程?

Not immediately. 不是立即。 The Task would be queued. 该任务将排队。

But the ThreadPool does manage its threads: when the queue fills up it will create new worker threads at a rate of 2 per second. 但是ThreadPool确实管理其线程:当队列填满时,它将以每秒2的速率创建新的工作线程。

And when the queue runs empty Threads will be destroyed at the same rate. 并且当队列运行时,空线程将以相同的速度销毁。

The actual algorithm is a little more involved (from .NET 4 on) but it does mean that the Pool does exercise some relatively simple resource management. 实际的算法要复杂得多(从.NET 4开始),但这确实意味着Pool确实执行了一些相对简单的资源管理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM