Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 available 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?

like image 539
Randy Minder Avatar asked Dec 09 '25 20:12

Randy Minder


2 Answers

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.

like image 57
Truong Hong Thi Avatar answered Dec 11 '25 10:12

Truong Hong Thi


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.

like image 25
Jon Skeet Avatar answered Dec 11 '25 09:12

Jon Skeet