How-to dispose a waithandle correctly
Asked Answered
C

1

6

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();
 ....
}
Cristen answered 27/4, 2010 at 14:37 Comment(0)
S
6

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.

Schlessel answered 27/4, 2010 at 14:52 Comment(2)
+ 1 - I completely overlooked the fact that Dispose is an explicit interface implementation (thanks, Adam!) - this is certainly the way to go.Donothing
Sounds reasonable. I already guessed that version 2 is the "cleanest" one. ThanksCristen

© 2022 - 2024 — McMap. All rights reserved.