Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How-to dispose a waithandle correctly

Tags:

c#

waithandle

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();
 ....
}
like image 384
TomTom Avatar asked Apr 27 '10 14:04

TomTom


1 Answers

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.

like image 91
Adam Robinson Avatar answered Sep 24 '22 12:09

Adam Robinson