如何使用这个信号量

时间:2011-02-19 11:21:20

标签: c# multithreading

        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("Thread for cui {0} in", cui));

        Thread.Sleep(5000);
        ResourceLock.Release();
    }

此代码一次只允许3个线程处于关键区域。但问题是,因为列表包含超过100万个recors,我得到一个OutOfMemoryException。我认为这是因为即使semaphor只允许3个线程进入关键区域,但是创建了等待信号量的100万个线程。我该如何更改代码以防止这种情况发生?请帮忙

1 个答案:

答案 0 :(得分:3)

你真的不想要一百万个线程。目前尚不清楚你在做什么,但看起来就好像Parallel.ForEach(...)会做你想要的一切,只需要很少的工作和充足的理智。

如果您只想强制实施3个主题:

Parallel.ForEach(cuis, new ParallelOptions { MaxDegreeOfParallelism = 3 },
        Worker);

使用:

public static void Worker(int cui)
{
    Debug.WriteLine(String.Format("Thread for cui {0} in", cui));
    Thread.Sleep(5000);
}

如果您真的想使用信号量,请使用WaitOne到循环:

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();
}