2011-03-11 69 views
6

嗨 当我使用下面的代码:如何处置ManualResetEvent的

myManualResetEvent.Dispose(); 

编译器给出了这样的错误:

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

howevr以下行正常工作:

((IDisposable)myManualResetEvent).Dispose(); 

是它的正确的方式处置或在运行时它可能会崩溃在一些场景。

谢谢。

+0

我认为你的示例代码可能有问题。如果编译器提供“'System.Threading.WaitHandle.Dispose(bool)'由于其保护级别而无法访问。”错误你必须使用myManualResetEvent.Dispose(true);或myManualResetEvent.Dispose(false); not myManualResetEvent.Dispose(); – 2017-04-21 13:29:20

回答

16

.NET基类库的设计者决定使用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. 
} 

或致电Close

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 .

3

WaitHandle.Close

This method is the public version of the IDisposable.Dispose method implemented to support the IDisposable interface.

2

根据the documentationWaitHandle.Dispose()WaitHandle.Close()是等价的。 Dispose存在以允许通过IDisposable接口关闭。用于手动关闭的WaitHandle(如ManualResetEvent的),就可以简单地使用Close而不是直接Dispose

WaitHandle.Close

[...] This method is the public version of the IDisposable.Dispose method implemented to support the IDisposable interface.