tags:

views:

143

answers:

1

Hello,

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();
 ....
}
+2  A: 

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 to null is 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 the WaitHandle is 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 the Dispose method from IDisposable is explicitly implemented and has identical code to Close) automatically takes care of disposing of the SafeWaitHandle. Don't do that yourself.

Adam Robinson
+ 1 - I completely overlooked the fact that Dispose is an explicit interface implementation (thanks, Adam!) - this is certainly the way to go.
Jeff Sternal
Sounds reasonable. I already guessed that version 2 is the "cleanest" one. Thanks
TomTom