如何处理ManualResetEvent?

7

您好,当我使用以下代码时:

 myManualResetEvent.Dispose();

编译器报错如下:
 'System.Threading.WaitHandle.Dispose(bool)' is inaccessible due to its protection level.

然而以下代码行可以正常工作:

 ((IDisposable)myManualResetEvent).Dispose();

这是正确的处理方式,但在某些情况下可能会导致运行时崩溃。

谢谢。


我认为你的示例代码可能有问题。如果编译器出现“'System.Threading.WaitHandle.Dispose(bool)'由于其保护级别而无法访问。”错误,那么你必须使用myManualResetEvent.Dispose(true);或myManualResetEvent.Dispose(false);而不是myManualResetEvent.Dispose(); - cahit beyaz
3个回答

17

.NET基类库的设计者决定使用显式接口实现来实现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();

您可以在MSDN的设计指南《实现Finalize和Dispose以清理非托管资源》中的自定义Dispose方法名称一节中了解更多信息:

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


3

WaitHandle.Close

此方法是实现IDisposable接口,支持IDisposable.Dispose方法的公共版本。


2
根据文档WaitHandle.Dispose()WaitHandle.Close()是等效的。 Dispose存在是为了通过IDisposable接口关闭。对于手动关闭WaitHandle(例如ManualResetEvent),您可以直接使用Close而不是Dispose

WaitHandle.Close

[...] 此方法是IDisposable.Dispose方法的公共版本,用于支持IDisposable接口。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接