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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…