I have a class with this field:
private WcfChannelFactory<IPrestoService> _channelFactory;
In the Dispose()
method, I'm doing this:
if (_channelFactory != null) { _channelFactory.Dispose(); }
But that produces an error:
Cannot access explicit implementation of IDisposable.Dispose
After doing some research, it appears that I can dispose this way:
if (_channelFactory != null) { (_channelFactory as IDisposable).Dispose(); }
I don't understand two things:
Why isn't Dispose()
available? WcfChannelFactory<T>
derives from ChannelFactory<T>
, which derives from ChannelFactory
, which implements IDisposable
. Yet ChannelFactory
doesn't have a Dispose()
method. How is this possible?
If I could (should?) simply call Close()
on _channelFactory
, why doesn't the XML documentation state that Close()
will also call Dispose()
? Maybe it won't? This is confusing.
Rule#1: Properly dispose of classes that implement IDisposable. The first rule is whenever you are consuming a class that implements the IDisposable interface; you should call the “Dispose” method when you are done with that class.
If you don't dispose FileStream class then it keeps the handle and file is held open for your program. Instance of FileStream goes to garbage collection, lives there for a short moment of time and then it's removed.
Implement the dispose pattern for a derived class Instead, to clean up a derived class, you provide the following: A protected override void Dispose(bool) method that overrides the base class method and performs the actual cleanup of the derived class. This method must also call the base. Dispose(bool) ( MyBase.
IDisposable is an interface that contains only a single method i.e. Dispose(), for releasing unmanaged resources. IDisposable is defined in the System namespace. It provides a mechanism for releasing unmanaged resources.
As the Dispose
method is implemented explicilty for the IDisposable
interface, you can only see the method when you have a reference of the type IDisposable
. The method is there, but you can't see it when you have a reference of a different type. It's similar to how a private method is only visible from code within the class itself, although it's always there.
The Close
method won't call Dispose
for this class. The method doesn't close the factory, it starts an asynchronous closing process. When the Close
method exits, the closing process is not finished, so the object can't be disposed at that time.
The Dispose
method was implemented as an explicit member of the interface IDisposable
. That is, the definition looks something like this:
public class WcfChannelFactory<T> : IDisposable
{
public void IDisposable.Dispose()
{
...
}
}
Tutorial: Explicit Interface Implementation Tutorial
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With