I’m doing some multi-threading and use AutoResetEvents and ManualResetEvents do control my main – loop. When “destryoing” the threads I also have to dispose these signals, that’s clear.
But I saw different ways how to dispose Waithandles, and I’m not sure which one is correct:
Version 1
if (disposing)
{
this.threadExitEvent.SafeWaitHandle.Dispose();
this.threadExitEvent.Close();
this.threadExitEvent = null;
....
}
Version 2
if (disposing)
{
this.threadExitEvent.Close();
this.threadExitEvent = null;
....
}
Version 3
if (disposing)
{
this.threadExitEvent.Close();
....
}
Version 2 is what I’d go with, as there’s (presumably) no need to hang on to your newly-disposed
WaitHandle, so setting it tonullis a good idea. This also makes it easier to adapt your object being able to recover from being disposed, as all you have to do is check to see if theWaitHandleis null and recreate it if so.That being said, nobody’s going to slap your hand for going with option 3.
Don’t use option 1; it’s generally a bad idea to “reach inside” of objects and start disposing members. Calling
Close(since theDisposemethod fromIDisposableis explicitly implemented and has identical code toClose) automatically takes care of disposing of theSafeWaitHandle. Don’t do that yourself.