Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Dispose ManualResetEvent

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.

like image 821
Azodious Avatar asked Mar 11 '11 08:03

Azodious


2 Answers

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.

like image 152
Martin Liversage Avatar answered Sep 28 '22 22:09

Martin Liversage


WaitHandle.Close

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

like image 22
Julien Roncaglia Avatar answered Sep 28 '22 21:09

Julien Roncaglia