c# – 如何处理ManualResetEvent

你好
当我使用以下代码时:
myManualResetEvent.Dispose();

编译器给出了这个错误:

'System.Threading.WaitHandle.Dispose(bool)' is inaccessible due to its protection level.

然后以下行正常工作:

((IDisposable)myManualResetEvent).Dispose();

它是正确的处理方式,或者在运行时它可能会在某些场景中崩溃.

谢谢.

解决方法

.NET Base Class Library的设计者决定使用 explicit interface implementation实现Dispose方法:
private void IDisposable.Dispose() { ... }

Dispose方法是私有的,调用它的唯一方法是将对象强制转换为IDisposable.

这样做的原因是将Dispose方法的名称自定义为更好地描述对象如何处置的内容.对于ManualResetEvent,自定义方法是Close方法.

要处理ManualResetEvent,您有两个不错的选择.使用IDisposable:

using (var myManualResetEvent = new ManualResetEvent(false)) {
  ...
  // IDisposable.Dispose() will be called when exiting the block.
}

或致电关闭:

var myManualResetEvent = new ManualResetEvent(false);
...
// This will dispose the object.
myManualResetEvent.Close();

您可以在设计指南中的Customizing a Dispose Method Name部分中阅读更多内容,在MSDN上实现最终化和处理以清理非托管资源:

Occasionally a domain-specific name is more appropriate than Dispose. For example,a file encapsulation might want to use the method name Close. In this case,implement Dispose privately and create a public Close method that calls Dispose.

相关文章

目录简介使用JS互操作使用ClipLazor库创建项目使用方法简单测...
目录简介快速入门安装 NuGet 包实体类User数据库类DbFactory...
本文实现一个简单的配置类,原理比较简单,适用于一些小型项...
C#中Description特性主要用于枚举和属性,方法比较简单,记录...
[TOC] # 原理简介 本文参考[C#/WPF/WinForm/程序实现软件开机...
目录简介获取 HTML 文档解析 HTML 文档测试补充:使用 CSS 选...