What does AutoResetEvent.Set() do ?

JAN picture JAN · Oct 9, 2015 · Viewed 7.8k times · Source

If I do this :

private static System.Threading.AutoResetEvent event_2 = new System.Threading.AutoResetEvent(false);

And then in Main thread I do :

event_2.Set();

It changes the state from false to true ?

If so , it basically does :

AutoResetEventState = !AutoResetEventState 

?

Answer

Jon Hanna picture Jon Hanna · Oct 9, 2015

It sets the state to one that allows threads to continue execution if they Wait() on it.

If there are any threads already waiting, then one will be allowed to progress and the state will immediately be set to not set, so all other threads will continue to block.

If there are no threads currently waiting then the first to wait will immediately be allowed through, but subsequent threads will block.

The same general mechanism is shared by other EventWaitHandle-derived classes, but the automatic resetting upon a thread being allowed to progress is different to ManualResetEvent, hence the names.

The initial state is signalled (allowing threads to progress) if true is passed to the constructor, and not signalled if false is passed, so passing true is the same as if you'd called Set() immediately after construction while passing false is conversely the same as if you'd called Reset().