我想做这样的事:
EventWaitHandle handler = new EventWaitHandle(false, EventResetMode.AutoReset)
//This code will run in background thread
private void AsyncWait() {
while (true) {
handler.WaitOne();
//LongRunningOperation()
}
}在代码的其他部分,将有一些方法调用:
handler.Set()所以执行LongRunningOperation()。
问题是,当handler.Set()线程运行LongRunningOperation()时,可以再次调用LongRunningOperation()。
这使得在LongRunningOperation()仍在执行LongRunningOperation()时,无论何时调用handler.Set()都不会调用AsyncWait()。
如何纠正这个问题?
发布于 2013-11-06 07:40:47
使用信号量代替AutoResetEvent。
信号量在内部使用计数器。您还可以定义一次可以“通过”的最大线程数。
readonly Semaphore _semaphore = new Semaphore(0, int.MaxValue);
public void Enqueue<T>(T item)
{
_internalQueue.Enqueue(item);
_semaphore.Release(); // Informs that deque task to unblock if waiting. Equivalent to the WaitHandle.Set() method. Increases the semaphore counter
}
public T Dequeue()
{
_semaphore.WaitOne(); // Blocks as long as there are no items in the queue. Decreases the semaphore counter when "let through". Blocks the thread as long as semaphore counter is zero.
return _internalQueue.Dequeue();
}https://stackoverflow.com/questions/19805507
复制相似问题