How to check if ManualResetEvent has been disposed, when trying to Set() it inside an EventHandler? How to check if ManualResetEvent has been disposed, when trying to Set() it inside an EventHandler? multithreading multithreading

How to check if ManualResetEvent has been disposed, when trying to Set() it inside an EventHandler?


ManualResetEvent.SafeWaitHandle.IsClosed

Seems strange, but the only thing that the dispose does is to close the safeHandler, which is the only object that its the dispose intended to...

The Dispose of the SafeWaitHandle, changes this property from False to True.


You can try to check it by the mre.SafeWaitHandle.IsClosed property


As a case try out using simple boolean switch which indicating whether setting manualResetEvent is actual:

bool isMreSync = true;var myObjectWithEvents = new ObjectWithEvents();using (var mre = new ManualResetEvent(false)) {    var onEvent = new EventHandler<EventArgs>((sender, e) =>                  {                      if (isMreSync)                     {                         mre.Set();                      }                 });  // try ... finally block   }isMreSync = false;

If event might be executed asynchronously - synchronize access to boolean switch.