Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disposing Samples c#

Tags:

c#

idisposable

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!

like image 408
Reyn Avatar asked Nov 27 '25 01:11

Reyn


1 Answers

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:

  • the Dispose(true) route will only be called via IDisposable - which typically means via using
  • the Dispose(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.

like image 70
Marc Gravell Avatar answered Nov 29 '25 18:11

Marc Gravell