Search code examples
c#manualresetevent

Regarding the use of ManualResetEvent usage c#?


i am not familiar with the usage of ManualResetEvent ?

is it thread related. what it does and when it is used?

here i got a code where ManualResetEvent is used but i just do not understand what it does?

here is the code

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();
  }

  // ...
} 

what is the meaning of _complete.WaitOne(); & _complete.Set(); ?

can anyone give me small sample code where ManualResetEvent class usage will be there.

looking for good discuss and usage of ManualResetEvent ? thanks


Solution

  • I suggest you to read the "remarks" section of the MSDN page of ManualResetEvent which is pretty clear about the usage of this class.

    To answer your specific question, the ManualResetEvent is used to simulate a synchronous call to Download even if it's asynchronous. It calls the async method and blocks until the ManualResetEvent is signaled. The ManualResetEvent is signaled within the event handler of the async event-based pattern. So basically it waits until the event is fired and the event handler is executed.