3

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?

Edwin
  • 527
  • 7
  • 15
  • 1
    The [docs for `Close`](https://msdn.microsoft.com/en-us/library/system.threading.waithandle.close(v=vs.110).aspx) say: _"Once this method is called, references to the current instance cause undefined behavior."_ Whether that's for new references to it, or existing ones such as your call to `WaitOne` isn't clarified. But I wouldn't want to try it... why not close/dispose it from the one doing the waiting? – James Thorpe Nov 23 '15 at 10:58
  • Because the waiting is optional, so it won't get disposed then if the waiting isn't done... – Edwin Nov 23 '15 at 11:12

1 Answers1

2

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

Niclas
  • 1,220
  • 6
  • 12
  • I think you can never know that threads are waiting. They could be descheduled 1 instruction before entering the wait and other threads could not tell. – usr Nov 23 '15 at 12:26
  • Thanks for your reply. So I give up this pattern. I found a managed implementation for an AutoResetEvent, and I might try my luck with that one: http://www.codeproject.com/Articles/244638/Managed-Thread-Synchronization – Edwin Nov 23 '15 at 12:37
  • @usr Exactly, that's why I think this is a bad pattern to rely on. I don't know enough about the scenario here to recommend some other solution, but it could be possible to implement some simple thread safe countdown where the thread signaling and closing handle checks count before closing handle to make sure all consumers are done with their task. Or simply reverse dependencies.. – Niclas Nov 23 '15 at 12:51