Do I need to Dispose() or Close() an EventWaitHandle?(我需要 Dispose() 或 Close() 一个 EventWaitHandle 吗?)
问题描述
如果我使用 EventWaitHandle
(或 AutoResetEvent
、ManualResetEvent
)在线程之间进行同步,那么我是否需要调用 Close()
或 Dispose()
方法,当我完成它时?
If I am using EventWaitHandle
(or AutoResetEvent
, ManualResetEvent
) to synchronise between threads then do I need to call the Close()
or Dispose()
methods on that event handle when I am done with it?
EventWaitHandle
继承自 WaitHandle
,后者实现了 IDisposable
.如果我没有在任何包含 EventWaitHandle
的类上实现 IDisposable
,FxCop 会抱怨.所以这表明我确实需要调用它.
EventWaitHandle
inherits from WaitHandle
, which implements IDisposable
. And FxCop complains if I don't implement IDisposable
on any class that contains an EventWaitHandle
. So this suggests that I do need to call it.
但是,这些 MSDN 使用示例都没有调用 Dispose()
或 Close()
:
However none of these MSDN usage examples call Dispose()
or Close()
:
http://msdn.microsoft.com/en-us/library/system.threading.eventwaithandle(VS.80).aspxhttp://msdn.microsoft.com/en-us/library/system.threading.manualresetevent(VS.80).aspxhttp://msdn.microsoft.com/en-us/library/system.threading.autoresetevent(VS.80).aspx
这只是微软无视自己建议的一个例子吗?
Is this just an example of Microsoft ignoring their own advice?
推荐答案
EventWaitHandle
的一次性资源实际上是一个SafeHandle
(包装在一个SafeWaitHandle代码>).
SafeHandle
实现了一个终结器,它最终确保释放必要的资源,因此让垃圾收集器/终结器线程处理它应该是安全的在这种情况下.
The disposable resource of an EventWaitHandle
is actually a SafeHandle
(wrapped in a SafeWaitHandle
). SafeHandle
implements a finalizer, which eventually makes sure the necessary resource is release, so it should be safe to let the garbage collector / finalizer thread handle it in this case.
但是,当不再需要资源时,显式调用 Dispose()
总是一个好主意.
However, it is always a good idea to explicitly call Dispose()
when the resource is no longer needed.
C# 3.0 in a Nutshell 中的线程章节陈述
这种做法(可以说)是可以接受的带有等待句柄,因为它们有一个轻操作系统负担(异步代表完全依赖这种机制释放他们的 IAsyncResult
的等待句柄).
This practice is (arguably) acceptable with wait handles because they have a light OS burden (asynchronous delegates rely on exactly this mechanism to release their
IAsyncResult
's wait handle).
这篇关于我需要 Dispose() 或 Close() 一个 EventWaitHandle 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我需要 Dispose() 或 Close() 一个 EventWaitHandle 吗?
基础教程推荐
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- MS Visual Studio .NET 的替代品 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- rabbitmq 的 REST API 2022-01-01