信号量无一例外地溢出到最大值

Vis*_*hal 2 c# semaphore

我需要在我的应用程序中使用信号量,其中包括多个线程.我的用法可能是常见的情况,但我坚持使用API​​.

在我的使用中,信号量可以从多个位置发布,而只有一个线程在信号量上等待.

现在,我要求信号量是二进制信号,即,我需要确保在多个线程同时发布到信号量的情况下,信号量计数保持为1,并且不会抛出任何错误.我怎样才能做到这一点.

简而言之,我需要以下代码才能工作.

private static Semaphore semaphoreResetMapView = new Semaphore(0, 1);  // Limiting the max value of semaphore to 1.

void threadWait(){
    while (true){
        semaphoreResetMapView.WaitOne();
        <code>
    }
}

void Main(){

    tThread = new Thread(threadWait);
    tThread.Start();

    semaphoreResetMapView.Release(1);
    semaphoreResetMapView.Release(1);
    semaphoreResetMapView.Release(1);  // Multiple Releases should not throw an error. Rather saturate the value of semaphore to 1.
}
Run Code Online (Sandbox Code Playgroud)

我将不胜感激任何帮助.

Jon*_*eet 6

听起来你真的不需要信号量 - 你只需要一个信号量AutoResetEvent.你的"发布"线程只会调用Set,等待的线程会调用WaitOne.

或者你可以使用Monitor.WaitMonitor.Pulse......