AutoResetEvent 重置方法
有人可以介绍 AutoResetEvent.Reset() 方法的用例吗? 我何时以及为什么要使用此方法? 我了解 WaitOne 和 Set,但这对我来说相当不清楚。
Could someone introduce an use case for AutoResetEvent.Reset() method ?
When and why I would like to use this method ?
I understand WaitOne and Set but this is quite unclear for me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
是的,只要等待事件的线程收到信号,
AutoResetEvent
就会自动重置其状态。但是,给定事件可能不再有效,并且自最初设置后没有线程等待AutoResetEvent
。在这种情况下,Reset
方法就变得有用了Yes the
AutoResetEvent
will automatically reset it's state whenever a thread which is waiting on the event is signaled. However it's possible that a given event is no longer valid and no thread has waited on anAutoResetEvent
since it was originally set. In that scenario theReset
method becomes useful看起来它只是继承自 EventWaitHandle。也许对于同样继承自该类的 ManualResetEvent 更有用?
Looks like it's just inherited from EventWaitHandle. Probably more useful with the ManualResetEvent which also inherits from that class?
该方法继承自基类
EventWaitHandle
,用于(重新)将AutoResetEvent
设置为其“阻止”状态。因为
AutoResetEvent
一旦收到信号就会自动进入该状态,因此您通常不会在代码中看到此方法,但对于从EventWaitHandle
派生的其他类来说,这会很重要更有用!The method is inherited from the base class
EventWaitHandle
and is used to (re)set anAutoResetEvent
to its "blocked" state.Because
AutoResetEvent
will automatically enter that state as soon as it's signalled, you'll typically never see this method used in code, but for other classes deriving fromEventWaitHandle
it would be much more useful!如果 AutoResetEvent 生产者想要清除事件,您可以使用 Reset()。这样,您就可以安全地“重置”事件,而不必知道当前是否已发出信号。如果生产者使用 WaitOne 来“重置”它自己的事件,则存在死锁的风险(即永远不会返回,因为事件没有发出信号且生产者线程被阻塞)。
If the AutoResetEvent producer wants to clear the event, you would use Reset(). This way, you can safely "reset" the event without having to know if it's currently signaled. If the producer used WaitOne to "reset" it's own event, there is a risk that you could deadlock (i.e. never return since the event isn't signaled and the producer thread is blocked).
重置:
示例,
使用 重置,
Reset:
Sample,
Using Reset,
使用 Reset() 时应使用 ManualResetEvent,因为当线程发出信号时 AutoResetEvent 会自行重置。
You should use ManualResetEvent when using Reset(), as AutoResetEvent resets itself when a thread has become signaled.