Why is ThreadPool.SetMinThreads not changing the minimum value?

Compiling and running using .NET 4.0 runtime, I have code like this:

int MinWorkerThreads, MaxWorkerThreads;
int MinCompletionPortThreads, MaxCompletionPortThreads;
ThreadPool.GetMinThreads(out MinWorkerThreads, out MinCompletionPortThreads);
ThreadPool.GetMaxThreads(out MaxWorkerThreads, out MaxCompletionPortThreads);
_logger.Info("Default thread pool settings min/max:");
_logger.Info("Worker thread: " + MinWorkerThreads + " / " + MaxWorkerThreads);
_logger.Info("IO thread    : " + MinCompletionPortThreads + " / " + MaxCompletionPortThreads);
_logger.Info("Setting minimum default worker thread count to " + Config.MinWorkerThreads);
if (!ThreadPool.SetMinThreads(Config.MinWorkerThreads, MinCompletionPortThreads))
{
    _logger.Warn("Unable to modify the minimum number of worker threads");
}
ThreadPool.GetMinThreads(out MinWorkerThreads, out MinCompletionPortThreads);
_logger.Info("Worker thread: " + MinWorkerThreads + " / " + MaxWorkerThreads);

      

and my log output looks like this:

Default thread pool settings min/max:
Worker thread: 4 / 32767
IO thread    : 4 / 1000
Setting minimum default worker thread count to 50
Worker thread: 50 / 32767

      

The value changes immediately, but not permanently.

Why am I doing this? Timer

use the default ThreadPool, and I've seen moments where a sudden series of tasks injected the system thread pool, silencing them, causing some timers that had to run every 15 seconds to linger over 60 seconds.

The problem is that when I give the same information in fifteen minutes at runtime using the same code, I get very different values:

Worker thread: 4 / 400
IO thread    : 4 / 400

      

Is there a better way to solve this problem without giving up the use System.Timers.Timer

? What would reset this value in a standalone C # application that is not related to IIS at all? If you are self-hosted ASP.NET, will this implicitly change the system thread pool setting?

+3


source to share


1 answer


I would suggest an alternative approach.

Remove all blocking code from ThreadPool. This is not what it is for.

If you have IO-bound operations, proceed asynchronously at each step.



If you have CPU bound operations, do not run them on ThreadPool threads.

By strictly following these rules, you will never have to mess with the ThreadPool parameters. As you noticed, there are too many .Net APIs that rely entirely on the responsive ThreadPool. If you are just sucking up threads, it is likely that, although many of you will choose, if you run your program long / hard enough, you will hit the limit again.

Use ThreadPool as it was intended ... short-lived logic, mostly for sorting I / O results in the right place.

+3


source







All Articles