Condividi tramite


When Building Multi-Threaded Applications using ThreadPool, Make the Number of Worker Threads Configurable

Just a simple thought, when creating a multi-threaded applications, make the number of threads configurable. ThreadPool has this behavior that it will immediately set the minimum worker threads equal to the number of logical processors in your machine, and set the maximum to 250 per logical processor, well documented in msdn (.Net Framework 2.0 SP1).

ThreadPool will create a new thread every half second, also documented in msdn. This behavior could lead to thread explosions, where there are too much threads fighting for limited resources (memory, lock, disk IO, processor, etc.). Your app may run slower if the thread creation is not managed wisely.

It is also a good idea to be able to throttle the application to use fewer threads. It is a good idea to be able to limit the number of threads in the system through configuration. Set the max number of threads by calling SetMaxThreads, and if the config value is less than the number of logical processors, do not forget to call SetMinThreads. Be aware that this can also lead to other issue, like thread starvation.

This is just an idea, if you have been writing multi-threaded applications using ThreadPool, probably you have thought about this already. Keep in mind, your application needs as few thread as possible, but not fewer.