简体   繁体   中英

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? Or would it just wait until there is one available?

[tl;dr] I'm currently enqueuing a some calls directly to the 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).

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.

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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