Living .NET...

Musings on .NET, and the like - Manoj G [MVP, Connected Systems Developer]

SetMaxThreads: A good addition to the ThreadPool class in 2.0

The ThreadPool class is very handy to developers. You could queue a method to run on a separate thread and forget about it, without worrying about managing the thread object or about a possible thread explosion scenario. That’s because the .NET ThreadPool keeps a tab on the number of executing threads, which I believe is a maximum of 25 per processor. This might sound just fine, but recently, I came across a situation where even 25 threads per processor looked expensive – I needed to limit the count to something like 10. Unfortunately, the ThreadPool class didn’t give me a method/property where I could set a thread count in the pool to something smaller.  I wasn’t adept enough to host the CLR, where I could tweak this count. Instead, I decided to write a simplistic wrapper over the ThreadPool class, which basically did these things:

  • Keep a count on the number of active threads (which I wanted to limit in the first place)
  • Maintain a queue to store requests is threads aren’t available
  • A timer implementation, where a thread periodically checks whether queued jobs can now be pushed to the thread pool

Quite obviously, this is a logical replica of the ThreadPool implementation itself, which is pretty wasteful. But that was until .NET Framework 1.1. In .NET 2.0, the ThreadPool class comes with this new method called SetMaxThreads – just what I craved for. You can use this to set the maximum number threads in the thread pool. There are two values to set here – one for the worker threads (which is more relevant in my case), and one for IO Port completion (this is useful for asynchronous IO operations).

Again, it is one's responsibility not to set an arbitrary high value of worker threads; Do I need to explain why?

Posted: Oct 06 2005, 08:18 PM by Manoj G | with 3 comment(s)
Filed under:

Comments

Manoj G said:

Is there a Max to SetMaxThreads?
# October 14, 2005 5:20 PM

Manoj G said:

In general the threadpool does a good job of not creating extraneous threads where they are not needed, using internal heuristics. Thus I would expect that most people won't need to modify the max value (unless it is too low).

Yes, there is a logical max to SetMaxThreads -- it is a C# int.
# November 12, 2005 12:36 AM

anonimoatacante@yahoo.es said:

Have you sample code ??

# April 18, 2007 3:52 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)