2013-03-27 21 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秒並且如果否一個名爲設置(),它會自動調用它並妨礙工作。