2013-08-06 27 views
2

我需要在包含多个线程的应用程序中使用信号量。我的用法可能是一种常见的情况,但是m停留在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. 
} 

我会很感激这方面的帮助。

+1

听起来你应该使用[ManualResetEvent的(http://msdn.microsoft.com/en-us/library/system.threading.manualresetevent .aspx)而不是“Semaphore”。 –

+0

我后来认识到,AutoResetEvent实际上是正确的解决方案... – vishal

回答

6

这听起来像你并不真的需要一个信号量 - 你只需要一个AutoResetEvent。您的“发布”线程只会呼叫Set,而等待的线程会呼叫WaitOne

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

+0

我想你的意思是ManualResetEvent,而不是AutoResetEvent ..其中一个问题的评论为我解答。不管怎么说,多谢拉。 – vishal

+0

@vishal:不,我的意思是'AutoResetEvent',它比'ManualResetEvent'更接近信号量。 (在一个信号量中,如果你多次调用'WaitOne'而没有任何'Release'操作,你会期望第二个呼叫被阻塞,对吧?) –

+0

对。我同意。事实上,我只是意识到,即使对于我当前的解决方案AUtoResetEvent也比ManualResetEvent更好。谢谢。 – vishal