How to remove ManualResetEvent Utility

Hi When I use the following code:

myManualResetEvent.Dispose(); 

The compiler throws this error:

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

How the following line works:

  ((IDisposable)myManualResetEvent).Dispose(); 

this is the right way of disposal or at run time, which may happen in some scenarios.

Thanks.

+6
multithreading c # idisposable dispose
source share
3 answers

The developers of the .NET base class library decided to implement the Dispose method using an explicit interface implementation :

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

The Dispose method is private, and the only way to call it is to pass an IDisposable as you discovered.

The reason for this is to configure the Dispose method name to better describe how the object is located. For ManualResetEvent custom method is the Close method.

To get rid of ManualResetEvent , you have two good options. Using IDisposable :

 using (var myManualResetEvent = new ManualResetEvent(false)) { ... // IDisposable.Dispose() will be called when exiting the block. } 

or call Close :

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

For more information, see Configuring the name of the deletion method in the Design Guide Implementing Finalize and Dispose to Clean Up Unmanaged Resources on MSDN

Sometimes a domain name is more suitable than Dispose . For example, encapsulating a file may require the use of the Close method name. In this case, execute Dispose privately and create a public Close method that calls Dispose .

+16
source share

WaitHandle.Close

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

+3
source share

According to the documentation , WaitHandle.Dispose() and WaitHandle.Close() equivalent. Dispose exists to allow closure using the IDisposable interface. To manually close WaitHandle (e.g. ManualResetEvent), you can simply use Close directly instead of Dispose :

WaitHandle.Close

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

+2
source share

All Articles