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 吗?
基础教程推荐
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
