Using TPL how do I set a max threadpool size
Solution 1
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.
Solution 2
Typically TPL determines a good "default" threadpool size. If you really need fewer threads, see How to: Create a Task Scheduler That Limits the Degree of Concurrency
Solution 3
You should investigate your performance problems first. There are various issues that may result in reduced utilization:
- Scheduling long-running tasks without the LongRunningTask option
- Trying to open more than two concurrent connections to the same web address
- Blocking for access to the same resource
- Trying to access the UI thread using Invoke() from multiple threads
In any case you have a scalability issue that can't be addressed simply by reducing the number of concurrent tasks. Your program may run in a two-,four-, or eight-core machine in the future. Limiting the number of scheduled tasks will simply lead to waste of CPU resources.
jgerstle
Updated on June 05, 2022Comments
-
jgerstle almost 2 years
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?