你好
当我使用以下代码时:
当我使用以下代码时:
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 nameClose
. In this case,implementdispose
privately and create a publicClose
method that callsdispose
.
原文地址:https://www.jb51.cc/csharp/98973.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。