Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a fixed-size ThreadPool in .NET?

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?

like image 690
DLauer Avatar asked Aug 18 '09 16:08

DLauer


People also ask

How do you create a fixed size thread pool in Java?

Method Description newFixedThreadPool(int) Creates a fixed size thread pool. newCachedThreadPool() Creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are available newSingleThreadExecutor() Creates a single thread.

What is thread pool size?

The size of a thread pool is the number of threads kept in reserve for executing tasks. It is usually a tunable parameter of the application, adjusted to optimize program performance. Deciding the optimal thread pool size is crucial to optimize performance.

How does ThreadPool work in C#?

Thread pool is a collection of threads which can be used to perform no of task in background. Once thread completes its task then it sent to the pool to a queue of waiting threads, where it can be reused. This reusability avoids an application to create more threads and this enables less memory consumption.

What is ThreadPool QueueUserWorkItem?

QueueUserWorkItem(WaitCallback) Queues a method for execution. The method executes when a thread pool thread becomes available. QueueUserWorkItem(WaitCallback, Object) Queues a method for execution, and specifies an object containing data to be used by the method.


1 Answers

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.

like image 195
Jon Skeet Avatar answered Sep 30 '22 05:09

Jon Skeet