Multithreading: final thoughts on the thread pool
Now that we’ve ended our study of the thread pool, you know that we’ve got two ways of spanning new threads for performing work in parallel: we can manage the thread lifetime by using the Thread class directly or we can rely on thread pool for managing threads for us. Since there are options, you might be wondering which option you should choose for your code.
Once more, there’s really no definitive answer: it all depends on your scenario. If I had to give an answer to that, I’d say that most of the time you’d be better using the thread pool instead of creating your own threads. There are, however, a couple of scenarios where you should create your threads explicitly. For instance:
- if you need to set the apartment type;
- if you need to set the type of thread (pool threads are always background threads);
- if the application will take a long time to end.
Btw, there are also some scenarios where you should be careful in relying on the thread pool. For instance, in ASP.NET apps, you shouldn’t forget that ASP.NET will also use it for its own work (everything should go well if you’re just queuing small tasks: just don’t get too greedy and start queuing work on the thread pool:))
For those that are worried with performance, I guess that using the pool will improve it for many scenarios (specially if we’re talking about parallelizing small tasks) because you’re amortizing the thread creation by using the same threads several times for different tasks.
The new .NET 4.0 thread pool introduces several new features which you can reuse when using the parallel library. This is really cool stuff and I’ll redirect you to Daniel Moth’s excellent blog for getting more details on this new feature.
And that’s it for now. In the next posts, we’ll keep looking at multithreaded