0

我正在尝试做这样的事情:

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()可以在AsyncWait()线程运行时再次调用LongRunningOperation()

这使得当仍在执行LongRunningOperation()时被调用时将永远不会被调用handler.Set()AsyncWait()LongRunningOperation()

如何做到这一点?:(

4

1 回答 1

1

使用信号量而不是 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();
}
于 2013-11-06T07:40:47.307 回答