Looking at the sample code of MSDN
// Design pattern for a base class.
public class Base: IDisposable
{
private bool disposed = false;
//Implement IDisposable.
public void Dispose()
{
Dispose(true); <---- 1 Here
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
// Free other state (managed objects).
}
// Free your own state (unmanaged objects).
// Set large fields to null.
disposed = true;
}
}
// Use C# destructor syntax for finalization code.
~Base()
{
// Simply call Dispose(false).
Dispose (false);
}
}
I don't seem to get the line of code pointed in the first arrow (<----- 1 Here).
I was confused in the first arrow as to Whom the Dispose belong. to the IDisposable or the virtual Dispose of the base?
Any Help that would help me is Great and Very much appreciated!
The purpose of the Dispose(true) / Dispose(false) is so that the real code - the virtual void Dispose(bool) - knows whether it is being called via dispose or finalize. The Dispose(bool) is specific to the class (the virtual method); IDisposable only has a parameterless Dispose() method. As such:
Dispose(true) route will only be called via IDisposable - which typically means via usingDispose(false) route will only be called via the garbage collector(note that the Dispose(true) route disables the finalization step once complete)
This boolean flag is important, because during finalization you can't touch any other managed resources (because order is non-deterministic) - only unmanaged. The fact that this method is virtual means that subclasses can add their own cleanup code into the mix.
In reality, though, it is very rare that you need to implement a finalizer; you should not add this much boilerplate routinely.
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