如何正确处理等待句柄
我正在做一些多线程处理,并使用 AutoResetEvents 和 ManualResetEvents 来控制我的主循环。当“销毁”线程时,我还必须处理这些信号,这是很清楚的。
但我看到了如何处理 Waithandles 的不同方法,我不确定哪一种是正确的:
版本 1
if (disposing)
{
this.threadExitEvent.SafeWaitHandle.Dispose();
this.threadExitEvent.Close();
this.threadExitEvent = null;
....
}
版本 2
if (disposing)
{
this.threadExitEvent.Close();
this.threadExitEvent = null;
....
}
版本 3
if (disposing)
{
this.threadExitEvent.Close();
....
}
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();
....
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我会选择版本 2,因为(大概)不需要保留新处理的
WaitHandle
,因此将其设置为null
是一个好主意。这也使得您的对象能够更容易地从被处置中恢复,因为您所要做的就是检查WaitHandle
是否为空,如果是则重新创建它。话虽这么说,没有人会因为你选择选项 3 而拍你的手。
不要使用选项 1;不要使用选项 1。 “进入”对象内部并开始处理成员通常是一个坏主意。调用
Close
(因为IDisposable
中的Dispose
方法是显式实现的,并且具有与Close
相同的代码)会自动进行处理处置SafeWaitHandle
。你自己不要这样做。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 tonull
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 theWaitHandle
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 theDispose
method fromIDisposable
is explicitly implemented and has identical code toClose
) automatically takes care of disposing of theSafeWaitHandle
. Don't do that yourself.