开发者

How to Dispose ManualResetEvent

Hi When i use following code:

 myManualResetEvent.Dispose();

Compiler gives this error:

 'System.Threading.WaitHandle.Dispose(bool)' is in开发者_如何学Caccessible 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.


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.


WaitHandle.Close

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜