首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用WaitHandle

使用WaitHandle
EN

Stack Overflow用户
提问于 2013-11-06 06:28:17
回答 1查看 677关注 0票数 0

我想做这样的事:

代码语言:javascript
复制
EventWaitHandle handler = new EventWaitHandle(false, EventResetMode.AutoReset)

//This code will run in background thread
private void AsyncWait() {
    while (true) {
        handler.WaitOne();
        //LongRunningOperation()
    }
}

在代码的其他部分,将有一些方法调用:

代码语言:javascript
复制
handler.Set()

所以执行LongRunningOperation()。

问题是,当handler.Set()线程运行LongRunningOperation()时,可以再次调用LongRunningOperation()

这使得在LongRunningOperation()仍在执行LongRunningOperation()时,无论何时调用handler.Set()都不会调用AsyncWait()

如何纠正这个问题?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-11-06 07:40:47

使用信号量代替AutoResetEvent。

信号量在内部使用计数器。您还可以定义一次可以“通过”的最大线程数。

代码语言:javascript
复制
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();
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19805507

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档