Using TPL how do I set a max threadpool size

c#-4.0, multithreading, task-parallel-library

Solution

The default `TaskScheduler` (obtained from `TaskScheduler.Default`) is of type (internal class) `ThreadPoolTaskScheduler`. This implementation uses the `ThreadPool` class to queue tasks (if the `Task` isn't created with `TaskCreationOptions.LongRunning` - in this case a new thread is created for each task).

So, if you want to limit the # of threads available to `Task` objects created via `new Task(() => Console.WriteLine("In task"))`, you can limit the available threads in the global threadpool like this:

// Limit threadpool size
int workerThreads, completionPortThreads;
ThreadPool.GetMaxThreads(out workerThreads, out completionPortThreads);
workerThreads = 32;
ThreadPool.SetMaxThreads(workerThreads, completionPortThreads);

The call to `ThreadPool.GetMaxThreads()` is done to avoid shrinking the `completionPortThreads`.

Note that this may be a bad idea - since all Tasks without a specified scheduler, and any number of other classes use the default ThreadPool, setting the size too low could cause side-effects: Starvation, etc.

Problem

I am using the TPL to add new tasks to the system thread pool using the function `Task.Factory.StartNew()`. The only problem is that I am adding a lot of threads and I think it is creating too many for my processor to handle. Is there a way to set a maximum number of threads in this thread pool?

Original source