Reputation: 147
I have done a bunch of reading on the dynamics and implications of multi-threading in a server app (starving the clr thread pool, etc.) but let's say for sake of argument I have EXACTLY 4 async processes I need to accomplish per request of my (asp.net) page... Now let's say time is the more critical element and my site should not experience heavy traffic. In this scenario, is it preferable to spawn 4 threads using the new Thread()
approach or the ThreadPool.QueueUserWorkItem method
?
My concern (and my point) here is that using the ThreadPool method
, it may create a thread pool that is too large than what I really want? When I only need 4 threads, can't I just spawn them myself to keep the number of allocated app domain, clr threads minimal?
Upvotes: 3
Views: 853
Reputation: 171246
Spawning a thread is a very costly and therefore high-latency operation. If you want to manage threads yourself, which would be reasonable but not required, you have to build a custom pool.
Using thread pool work items is not without danger because it does not guarantee you a concurrency level of 4. If you happen to get 2 or 3 you will have much more latency in your HTTP request.
I'd use the thread-pool and use SetMinThreads
to ensure that threads are started without delay and that there are always enough.
Upvotes: 2
Reputation: 62459
I would definitely go for the ThreadPool
approach. It's designed for exactly this kind of scenario. The thread pool will internally manage the number of threads required, making sure not to overburden the system. Quoting from MSDN:
The thread pool provides new worker threads or I/O completion threads on demand until it reaches the minimum for each category. When a minimum is reached, the thread pool can create additional threads in that category or wait until some tasks complete. Beginning with the .NET Framework 4, the thread pool creates and destroys worker threads in order to optimize throughput, which is defined as the number of tasks that complete per unit of time. Too few threads might not make optimal use of available resources, whereas too many threads could increase resource contention.
If you're really paranoid you can limit it manually with SetMaxThreads
. Going for the manual threading management will only introduce potential bugs.
If you have access to .net 4.0 you can use the TPL Task
class (it also uses the ThreadPool
under the hood), as it has even more appealing features.
Upvotes: 1