Skip to content

Instantly share code, notes, and snippets.

@xiaomi7732
Last active December 30, 2022 01:19
Show Gist options
  • Save xiaomi7732/e12f045a805c68b8d30b8c1cdd1cde71 to your computer and use it in GitHub Desktop.
Save xiaomi7732/e12f045a805c68b8d30b8c1cdd1cde71 to your computer and use it in GitHub Desktop.
Customize thread pool defaults, avoid the caveats

Customize thread pool defaults, avoid the caveats

.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);

Caveat - settings will fail if the min value given is greater than the max

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment