2013-03-27 40 views
11

我不熟悉ManualResetEvent的用法吗?关于使用ManualResetEvent用法c#?

它是否与线程相关。它做什么以及何时使用?

这里我得到了一个代码,其中使用了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(); ?

意思谁能给我小的样本代码,其中的ManualResetEvent类的使用将在那里。

寻找良好的ManualResetEvent的讨论和用法?谢谢

回答

16

我建议你阅读MSDN page of ManualResetEvent的“备注”部分,这个部分很清楚这个类的用法。

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

2

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

2

为了达到对任何科目的深刻理解,我必须阅读几乎相同的信息换句话说。 我读过有关ManualResetEvent的MSDN文档,这是很好的我差点去​​了解它,但这种联系帮助我理解得很好:

http://dotnetpattern.com/threading-manualresetevent


很简单的解释

如果当前线程调用WiatOne()方法,它将等待(因此停止任何操作),直到其他线程调用Set()方法。

WaitOne有另一个过载,WaitOne(TimeSpan)。 这与上面几乎相同,但如果对于此示例给出5秒时间,则当前线程将等待其他线程调用Set()方法5秒并且如果否一个名为设置(),它会自动调用它并妨碍工作。