Vitali Petrov
Vitali Petrov

Reputation: 154

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?

Upvotes: 3

Views: 638

Answers (1)

Emond
Emond

Reputation: 50672

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.

Upvotes: 4

Related Questions