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 吗?
基础教程推荐
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 如果条件可以为空 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 将数据集转换为列表 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
