我需要在包含多个线程的应用程序中使用信号量。我的用法可能是很常见的情况,但仍受API困扰。
在我的用法中,可以从多个位置张贴信号量,而只有一个线程在信号量上等待。
现在,我要求信号量是二进制的,即,我需要确保在多个线程同时发布到信号量的情况下,信号量保持为一,并且不会引发错误。我该怎么做。
简而言之,我需要以下代码才能工作。
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.
}
我将不胜感激。
最佳答案
听起来您实际上并不需要信号灯-您只需要AutoResetEvent
。您的“发布”线程将仅调用Set
,而等待线程将调用WaitOne
。
或者您可以只使用Monitor.Wait
和Monitor.Pulse
...