Threading Question - What happens if no threads available in the thread pool?
I have the following code:
CancellationTokenSource cancelSource = new CancellationTokenSource();
_cancelTokenList.Add(cancelSource);
CancellationToken token = cancelSource.Token;
Task.Factory.StartNew(() =>
{
StartTest(token);
}, token);
Will an exception get thrown if no threads are a开发者_运维技巧vailable to service the request for a new task, or will it just wait until a thread becomes available? If it waits, how long will it wait?
From MSDN:
You can queue as many thread pool requests as system memory allows. If there are more requests than thread pool threads, the additional requests remain queued until thread pool threads become available.
The threads in the managed thread pool are background threads. That is, their IsBackground properties are true. This means that a ThreadPool thread will not keep an application running after all foreground threads have exited.
It will waits until one is available, or your application exits.
It will just wait until a thread is available. As far as I'm aware, it will wait as long as it takes to get a thread. If you cancel it while it's still waiting for a thread, it just becomes cancelled immediately, and the user code will never run.
A Task is handed to a Scheduler. The (default) TPL scheduler manages a handful of Worker Threads and assigns the Tasks to those Threads. If no Thread is available your Task will wait in a Queue. If too many Tasks are queuing up the scheduler/threadpool will slowly create new Threads (at a rate of 2 / second).
You show but don't mention a CancellationToken. It can only be used to request a cancellation so I suspect your StartTest() will be executed even if the token was cancelled while the Task was queued.
精彩评论