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?
I am using the TPL to add new tasks to the system thread pool
Share
The default
TaskScheduler(obtained fromTaskScheduler.Default) is of type (internal class)ThreadPoolTaskScheduler. This implementation uses theThreadPoolclass to queue tasks (if theTaskisn’t created withTaskCreationOptions.LongRunning– in this case a new thread is created for each task).So, if you want to limit the # of threads available to
Taskobjects created vianew Task(() => Console.WriteLine("In task")), you can limit the available threads in the global threadpool like this:The call to
ThreadPool.GetMaxThreads()is done to avoid shrinking thecompletionPortThreads.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.