ThreadPool in Whidbey with an Example

If you have used the ThreadPool in .NET 1.x, you know that the threadpool defaults to ( 25 * number of processors ) threads per process.  It can be changed, but it is kinda complicated to track down how to change this.  Well, MS has made changing the threadpool to make this easily changeable.  Here is some example code:

ThreadPool.GetMaxThreads(out iMaxThrds, out iThrdCompletionPT);

ThreadPool.SetMaxThreads(Environment.ProcessorCount * 50, iThrdCompletionPT);

ThreadPool.GetMaxThreads(out iMaxThrds, out iThrdCompletionPT);

The first time that ThreadPool.GetMaxThreads is called, the value I recieved is 25, which is what I would expect from a system with 1 cpu.  I then call back to SetMaxThreads with the value of 50 times the number of cpus.  when I make the second call into ThreadPool.GetMaxThreads(), i get back the value of 50.  So, if you have exhausted your threadpoll threads, this is a way to get more threads into your threadpool.  One thing that I wanted to mention, this will not change the number of threads that are used by the threadpool.  If the threadpool still thinks that you don't need any more threads, then you won't really get anything by increasing the number of threads in the threadpool.  This is only going to be useful if you have depleted the number of threads in your threadpool.  For example, you have a web application, that makes a web services request, well that will use two threads, one to service the request and another to make the web service request.  Get a bunch of responses, and you might run out of threads in your threadpool.

Wally

 

No Comments