我已经阅读了关于这方面的文档,我想我明白了。AutoResetEvent在代码通过event.WaitOne()时重置,但ManualResetEvent不会。
这对吗?
我已经阅读了关于这方面的文档,我想我明白了。AutoResetEvent在代码通过event.WaitOne()时重置,但ManualResetEvent不会。
这对吗?
当前回答
是的。这就像收费站和门的区别。ManualResetEvent是门,需要手动关闭(重置)。AutoResetEvent是一个收费站,允许一辆车通过,在下一辆车通过之前自动关闭。
其他回答
autoResetEvent.WaitOne ()
类似于
try
{
manualResetEvent.WaitOne();
}
finally
{
manualResetEvent.Reset();
}
作为原子操作
是的。这是绝对正确的。
您可以将ManualResetEvent视为指示状态的一种方式。某些东西打开(设置)或关闭(重置)。有一定持续时间的事件任何等待该状态发生的线程都可以继续。
AutoResetEvent更类似于信号。这是发生了什么事的一个迹象。没有任何持续时间的事件。通常情况下(但不一定)发生的“事情”很小,需要由单个线程处理——因此在单个线程消耗事件后自动重置。
如果你想理解AutoResetEvent和ManualResetEvent,你需要理解的不是线程,而是中断!
. net希望尽可能地实现底层编程。
中断是在低级编程中使用的,它相当于一个信号从低电平变成高电平(反之亦然)。当这种情况发生时,程序中断其正常执行,并将执行指针移到处理此事件的函数上。
当中断发生时,要做的第一件事是重置它的状态,因为硬件是这样工作的:
a pin is connected to a signal and the hardware listen for it to change (the signal could have only two states). if the signal changes means that something happened and the hardware put a memory variable to the state happened (and it remain like this even if the signal change again). the program notice that variable change states and move the execution to a handling function. here the first thing to do, to be able to listen again this interrupt, is to reset this memory variable to the state not-happened.
这就是ManualResetEvent和AutoResetEvent之间的区别。 如果ManualResetEvent发生,我不重置它,下次发生时,我将无法收听它。
简短的回答是肯定的。最重要的区别是AutoResetEvent只允许一个等待线程继续。另一方面,ManualResetEvent将继续允许线程,甚至同时允许几个线程继续,直到您告诉它停止(重置它)。
想象一下AutoResetEvent将WaitOne()和Reset()作为单个原子操作执行。
AutoResetEvent还保证只释放一个等待线程。