List<int> cuis = PersistencyServices.GetListOfAllCui();
ResourceLock = new Semaphore(3, 5);
foreach (var cui in cuis)
{
Thread workThread = new Thread(new ParameterizedThreadStart(Worker));
workThread.Start(cui);
}
}
public static void Worker(object cui)
{
ResourceLock.WaitOne();
Debug.WriteLine(String.Format("Thre开发者_JAVA百科ad for cui {0} in", cui));
Thread.Sleep(5000);
ResourceLock.Release();
}
This code only allows 3 threads to be in the critical region at a time. But the problem is that because the list contains more that 1 million recors I get a OutOfMemoryException. I think this is because even if the semaphor only allows 3 threads to enter the critical region, but 1 million threads are created that wait for the semaphore. How should I change my code to prevent this? Please help
You really don't want a million threads. It isn't clear what you are doing, but it looks like maybe a Parallel.ForEach(...)
will do everything you want here, with little work and plenty of sanity.
If you want to enforce 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 the semaphore, use the WaitOne
to the 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();
}
精彩评论