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?
Thread-Pool pattern states, the work items are queued and the free threads in thread pool takes one from this queue. TPL however store the items (tasks) to queues of threads and work-stealing works if needed...
The maximum allowed number of processing threads in a pool is 1023. The pool allocates a maximum of 1000 threads in an I/O operation. To get maximum number of threads, you can use the GetMaxThreads method of the ThreadPool static class.
The size of a thread pool is the number of threads kept in reserve for executing tasks. It is usually a tunable parameter of the application, adjusted to optimize program performance. Deciding the optimal thread pool size is crucial to optimize performance.
A thread pool is a collection of threads which are assigned to perform uniformed tasks. The advantages of using thread pool pattern is that you can define how many threads is allowed to execute simultaneously.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With