加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何处理ManualResetEvent

发布时间:2020-12-15 18:35:08 所属栏目:百科 来源:网络整理
导读:你好 当我使用以下代码时: myManualResetEvent.Dispose(); 编译器给出了这个错误: 'System.Threading.WaitHandle.Dispose(bool)' is inaccessible due to its protection level. 然后以下行正常工作: ((IDisposable)myManualResetEvent).Dispose(); 它是
你好
当我使用以下代码时:
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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读