如何处理ManualResetEvent [英] How to Dispose ManualResetEvent

查看:180
本文介绍了如何处理ManualResetEvent的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨 当我使用以下代码时:

Hi When i use following code:

 myManualResetEvent.Dispose();

编译器给出此错误:

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

howevr下面的行工作正常:

howevr following line works fine:

 ((IDisposable)myManualResetEvent).Dispose();

这是处理的正确方法,还是在运行时可能会在某些场景中崩溃.

is it the correct way to dispose or at runtime it might crash in some scenerios.

谢谢.

推荐答案

.NET基础类库的设计人员决定使用

The designers of the .NET Base Class Library decided to implement the Dispose method using explicit interface implementation:

private void IDisposable.Dispose() { ... }

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

The Dispose method is private and the only way to call it is to cast the object to IDisposable as you have discovered.

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

The reason this is done is to customize the name of the Dispose method into something that better describes how the object is disposed. For a ManualResetEvent the customized method is the Close method.

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

To dispose a ManualResetEvent you have two good options. Using IDisposable:

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

或致电Close:

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

您可以在在设计指南在MSDN上实施最终确定和处置以清理非托管资源中自定义处置方法名称:

You can read more in the section Customizing a Dispose Method Name in the design guideline Implementing Finalize and Dispose to Clean Up Unmanaged Resources on MSDN:

有时,特定于域名的名称比Dispose更合​​适.例如,文件封装可能要使用方法名称Close.在这种情况下,请私下实现Dispose并创建一个调用Dispose的公共Close方法.

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.

这篇关于如何处理ManualResetEvent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆