开发者

How-to dispose a waithandle correctly

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.th开发者_运维知识库readExitEvent = 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 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜