views:

487

answers:

5

Hi,

I want to create a fixed arbitrary size ThreadPool in .NET - I understand the default size is 25 - but I wish to have a different size e.g. 5 or 10. Anyone?

+2  A: 
ThreadPool.SetMaxThreads()
Ben M
Is there another non-static way? Won't this make all ThreadPools that size - I only want a single instance of a ThreadPool to have a particular size.
DLauer
There is only one BCL ThreadPool per process. If you want a thread pool for just your scenario, you'd have to find a third-party library.
Ben M
It's probably worthy of note that you can't do this in runtime 1.1. Of course, exceptions in threads can cause memory corruption in 1.1, so you should not use it if at all possible.
quillbreaker
A: 

ThreadPool.SetMaxThreads(5,5) and then anything over five threads will get queued.

Mark
A: 

You want the ThreadPool.SetMaxThreads() method.

maxpower47
+3  A: 

You can use ThreadPool.SetMinThreads and ThreadPool.SetMaxThreads to have some control over the number of threads in the thread pool.

That being said, I recommend being cautious in using this. It's easy to get yourself into trouble, as many operations in the BCL rely on threadpool threads being available.

Reed Copsey
+2  A: 

You should be careful about changing the size of the thread pool. There is just one fixed system thread pool, used by all kinds of things. Making it too small could cause problems in areas you didn't even think you were using.

If you want to have a relatively small thread pool for one specific task, you should use a separate pool. There are various third party pools available - I have a rather old one as part of MiscUtil, but it should be good enough for simple use cases. I'm sure you can find more advanced ones if you look.

It's unfortunate that there isn't an instantiable ThreadPool in the framework yet. I can't remember offhand whether Parallel Extensions will effectively provide one, but I don't think it will.

Jon Skeet
The Parallel Extensions in .NET 4.0 will actually use the standard ThreadPool from the base class library. They will not provide their own. (The BCL ThreadPool class was improved in .NET 4 to add many features required to get the parallel extensions to work efficiently, which in turn improves it in quite a few ways. For example, it has a much better scheduler than the .NET 3.5 ThreadPool.)
Reed Copsey
@Reed: Yup, I knew about the normal bit of PFX using the system threadpool... I wasn't sure whether there was a new one that could be created as well. Ah well.
Jon Skeet