You really don't want a million threads. It's not clear what you are doing, but it seems that Parallel.ForEach(...) will do everything you need with a little work and a lot of sanity.
If you want to use only 3 threads:
Parallel.ForEach(cuis, new ParallelOptions { MaxDegreeOfParallelism = 3 }, Worker);
with:
public static void Worker(int cui) { Debug.WriteLine(String.Format("Thread for cui {0} in", cui)); Thread.Sleep(5000); }
If you really want to use a semaphore, use WaitOne in a loop:
foreach (var cui in cuis) { ResourceLock.WaitOne(); Thread workThread = new Thread(new ParameterizedThreadStart(Worker)); workThread.Start(cui); } ... public static void Worker(object cui) { Debug.WriteLine(String.Format("Thread for cui {0} in", cui)); Thread.Sleep(5000); ResourceLock.Release(); }
source share