Tho*_*mas 11 c# manualresetevent
我不熟悉ManualResetEvent的用法?
它与线程有关吗?它做什么以及何时使用?
在这里我得到了一个使用ManualResetEvent的代码,但我只是不明白它的作用?
这是代码
public class Doc : SomeInterfaceFromTheDll
{
private readonly IVersion version; // An interface from the DLL.
private readonly ManualResetEvent _complete = new ManualResetEvent(false);
private bool downloadSuccessful;
// ...
public bool Download()
{
this.version.DownloadFile(this);
// Wait for the event to be signalled...
_complete.WaitOne();
return this.downloadSuccessful;
}
public void Completed(short reason)
{
Trace.WriteLine(string.Format("Notify.Completed({0})", reason));
this.downloadSuccessful = reason == 0;
// Signal that the download is complete
_complete.Set();
}
// ...
}
Run Code Online (Sandbox Code Playgroud)
的意义是什么 _complete.WaitOne(); & _complete.Set(); ?
任何人都可以给我一些小样本代码,其中包含ManualResetEvent类的用法.
寻找好的讨论和使用ManualResetEvent?谢谢
ken*_*n2k 17
我建议你阅读MSDN页面ManualResetEvent的"备注"部分,其中非常清楚这个类的用法.
要回答您的具体问题,即使它是异步的,它ManualResetEvent也用于模拟同步调用Download.它调用异步方法并阻塞,直到ManualResetEvent发出信号.该ManualResetEvent是基于事件的异步模式的事件处理程序中发出信号.所以基本上它会等到事件被触发并执行事件处理程序.
为了深入理解任何主题,换句话说,我必须阅读几乎相同的信息。我已经阅读了有关 ManualResetEvent 的 MSDN 文档,很好,我几乎要理解它了,但是这个链接帮助我很好地理解了它:
http://dotnetpattern.com/threading-manualresetevent
非常简单的解释
如果当前线程调用WiatOne()方法,它将等待(因此停止执行任何操作),直到任何其他线程调用Set()方法。
WaitOne 的另一个重载是WaitOne(TimeSpan)。这和上面的几乎一样,但是如果例如给这个方法5 秒的时间,当前线程将等待其他线程调用Set()方法5 秒 ,如果没有人调用Set(),它自动调用它并继续工作。