Limiting the number of threads

In our project we faced a problem how to make running some calculations concurrently. We can simply start each calculation in a separate thread but the problem is how to limit the number of threads.

The first idea was to use ThreadPool from .NET library. We could easily limit the number of threads using ThreadPool.SetMaxThreads. But here we have another problem: imagine, that our application uses threads somewhere else, or even more – some of the referenced libraries use threads internally. ThreadPool is a static class and setting its maximal number of concurrent threads may break other stuff.

All we want is to limit number of threads which we use locally. So, here we come to the necessity of implementing our own local thread pool. Of course, you can use existent implementation such as Smart Thread Pool. Unfortunately, in our case we are limited to .NET 3.5 and adding additional third-party library is a problem.

Continue reading Limiting the number of threads