How to Dispose ManualResetEvent

戏子无情 提交于 2020-07-20 09:10:54

问题


Hi When i use following code:

 myManualResetEvent.Dispose();

Compiler gives this error:

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

howevr following line works fine:

 ((IDisposable)myManualResetEvent).Dispose();

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

Thanks.


回答1:


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

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

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

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.

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.
}

or calling Close:

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

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:

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.




回答2:


WaitHandle.Close

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




回答3:


According to the documentation, WaitHandle.Dispose() and WaitHandle.Close() are equivalent. Dispose exists to allow closing though the IDisposable interface. For manually closing a WaitHandle (such as a ManualResetEvent), you can simply use Close directly instead of Dispose:

WaitHandle.Close

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



来源:https://stackoverflow.com/questions/5270701/how-to-dispose-manualresetevent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!