如何处理ManualResetEvent [英] How to Dispose 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.
谢谢.
推荐答案
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 nameClose
. In this case, implementDispose
privately and create a publicClose
method that callsDispose
.
这篇关于如何处理ManualResetEvent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!