如何正确处理等待句柄

发布于 2024-08-30 03:00:49 字数 537 浏览 2 评论 0原文

我正在做一些多线程处理,并使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

跨年 2024-09-06 03:00:49

我会选择版本 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 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文