[英]Using WaitHandle
我正在嘗試做這樣的事情:
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()
如何做到這一點? :(
使用信號量而不是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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.