繁体   English   中英

关于使用ManualResetEvent的用法c#?

[英]Regarding the use of ManualResetEvent usage c#?

我不熟悉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();
  }

  // ...
} 

_complete.WaitOne(); & _complete.Set(); ?的含义是什么_complete.WaitOne(); & _complete.Set(); ? _complete.WaitOne(); & _complete.Set(); ?

任何人都可以给我一些小样本代码,其中包含ManualResetEvent类的用法。

寻找好的讨论和使用ManualResetEvent? 谢谢

我建议你阅读ManualResetEventMSDN页面的“备注”部分,它非常清楚这个类的用法。

为了回答您的具体问题, ManualResetEvent用于模拟对Download的同步调用,即使它是异步的。 它调用异步方法并阻塞,直到发出ManualResetEvent信号。 ManualResetEvent在基于异步事件的模式的事件处理程序中发出信号。 所以基本上它会等到事件被触发并执行事件处理程序。

为了深入理解任何主题,我必须阅读几乎相同的信息。 我已经阅读了有关ManualResetEvent的MSDN文档,我很了解它很好,但这个链接帮助我理解它:

http://dotnetpattern.com/threading-manualresetevent


非常简单的解释

如果当前线程调用WiatOne()方法,它将等待(所以停止做任何事情),直到任何其他线程调用Set()方法。

WaitOne还有另一个重载,就是WaitOne(TimeSpan) 这与上面的几乎相同,但是如果对于eaxample给这个方法5秒的时间,当前线程将等待其他线程调用Set()方法5秒 ,如果没有人调用Set() ,它自动调用它并使工作恢复正常。

ManualSetEvent是一个类,它可以帮助您管理不同线程之间的通信,当一些线程必须停止并等待完成另一个线程(线程)然后该类非常有用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM