Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When AutoResetEvent is Reset?

I still can't understand how AutoResetEvent works even after using it for years.

When it comes to Set(), should there be a part of code somewhere awaiting for WaitOne()?.

In other words.. if Set() has been successfully called before WaitOne(), will it be Reset automatically before WaitOne() and then I will miss Set?

or in other words - Does WaitOne() makes the flag reset or not?

like image 245
Vitali Petrov Avatar asked Mar 12 '26 22:03

Vitali Petrov


1 Answers

From the documentation:

The Set method releases a single thread. If there are no waiting threads, the wait handle remains signaled until a thread attempts to wait on it, or until its Reset method is called.

So to answer the questions:

  • There does not have to be a WaitOne call, Reset will also un-signal the handle. (it would be bad design to make a class dependent on proper behavior of other classes.
  • The handle remains signaled until a thread wait for the handle or Reset is called on the AutoResetEvent. So the Set will not be missed. A Set can be missed when two threads wait. See the documentation:

There is no guarantee that every call to the Set method will release a thread. If two calls are too close together, so that the second call occurs before a thread has been released, only one thread is released - as if the second call did not happen. Also, if the Set method is called when there are no threads waiting and the AutoResetEvent is already signaled, the call has no effect.

  • WaitOne does un-signal the handle but not every wait is guaranteed to do that (see previous remark)

From your questions I get the impression that it would help you to read the documentation more carefully and perhaps have a look at the source code You will see that the .NET classes wrap the Windows Event object. See this article to get more information on how the Event object is/can be used.

like image 173
Emond Avatar answered Mar 15 '26 12:03

Emond



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!