This is easy to handle using TPL (parallel task library). It would look like
ParallelOptions options = new ParallelOptions() { MaxDegreeOfParallelism = 4 }; Parallel.ForEach(accounts, options, a => { ProcessAccount(a); });
http://msdn.microsoft.com/en-us/library/dd782721.aspx
Please note that TPL may decide to start less than 4 simultaneous threads, but will not work more than 4 based on the specified options. He can do this, for example, if he determines that the provided lamda (which calls ProcessAccount) is connected to the CPU and the system has less than 4 processor cores. Typically, especially in .NET 4.5, TPL makes very good decisions about the number of threads used.
As @Servy notes in the comments, if you don’t have any special reason to limit the code to 4 threads, it’s best to just let TPL sort how many threads to use on your own. Thus, if the same code runs on a 128-core processor in 2018, after you move on to other things, it can use all 128 cores).
Eric J.
source share