Search code examples
c#multithreadingwaithandleevent-wait-handle

Is it safe to call .Close (.Dispose) on an EventWaitHandle directly after .Set?


I have one thread waiting on an EventWaitHandle (AutoResetEvent):

AutoResetEvent.WaitOne();

I have another thread signalling the first thread to continue

AutoResetEvent.Set();
AutoResetEvent.Close();

Is it safe to call .Close direct after .Set, in other words will it be guaranteed that the waiting thread has continueed before the AutoResetEvent is disposed?


Solution

  • Yes, it is safe if things work out exactly as described in your question. If you know that all threads were already waiting when you called set, those threads will have been signaled and everything will be fine since all threads that are waiting are guaranteed to be released before a call to set returns.

    However, if you for some reason experience a race and call set and close before the thread has started to wait you will get a exception when trying to wait. So in practice you are better off avoiding this pattern. IMHO