.NET runtime allows customize default thread pool settings. There are essentially 4 values that could be customized:
- Minimum worker thread count;
- Minimum IO thread count;
- Maximum worker thread count;
- Maximum IO thread count;
And there are 4 primary APIs, 2 to read min/max, 2 to set those values:
- ThreadPool.GetMinThreads
- ThreadPool.GetMaxThreads
- ThreadPool.SetMinThreads
- ThreadPool.SetMaxThreads
For example:
These lines reads the minimum and maximum thread settings:
ThreadPool.GetMinThreads(out int workerThreads, out int completionPortThreads);
Console.WriteLine("Min Worker Threads: {0}, completion port threads: {1}", workerThreads, completionPortThreads);
ThreadPool.GetMaxThreads(out int maxWorkerThreads, out int maxCompletionPortThreads);
Console.WriteLine("Max worker threads: {0}, completion port threads: {1}", maxWorkerThreads, maxCompletionPortThreads);
Assuming on a box, these are the defaults
Min Worker Threads: 8, completion port threads: 1
Max worker threads: 32767, completion port threads: 1000
This would fail:
bool result = ThreadPool.SetMinThreads(32, 1001); // Expect to return false since 1001 > 1000.
Console.WriteLine("Set #1 result: {0}", result);
Tips: a boolean is returned to indicating whether the operation succeeded or not.
To make it work, enlarge the max first:
ThreadPool.SetMaxThreads(maxWorkerThreads, maxCompletionPortThreads + 1);
result = ThreadPool.SetMinThreads(32, 1001); // This will success, since the max of IO pool thread count is now 1001.
Tips: The set API requires 2 parameters. If you only want to change 1 value, read and pass back the original value. Just like the maximum worker thread pool thread count above.