Regarding the use of ManualResetEvent usage c#?
Asked Answered
B

3

14

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

Bolger answered 27/3, 2013 at 10:13 Comment(0)
S
18

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.

Sorbian answered 27/3, 2013 at 10:23 Comment(0)
V
5

To achieve deep understanding of any subject, I have to read the almost same information in other words. I've read the MSDN documentation about the ManualResetEvent, it was good I almost got to understand it, but this link helped me to understand it well:

http://dotnetpattern.com/threading-manualresetevent


VERY Simple explanation

If the current thread calls the WiatOne() method, it will be waiting(so stop doing anything) until any other thread calls the Set() method.

There is another overload for the WaitOne, is the WaitOne(TimeSpan). This is almost the same as the above, but if for eaxample give 5 seconds time to this method, the current thread will be waiting for other thread to call the Set() method for 5 seconds and if no one called Set(), it calls it automatically and contunie the work.

Verbosity answered 22/2, 2017 at 8:45 Comment(0)
V
4

ManualSetEvent is class that helps you to manage communication between different threads when some thread must be stopped and wait to finish another thread (threads) then that class is very usefull.

Vitek answered 4/2, 2015 at 14:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.