Finalizers with Dispose () in C #

See sample code from MSDN: ( http://msdn.microsoft.com/en-us/library/b1yfkh5e (v = VS.100) .aspx )

// Design pattern for a base class.
public class Base: IDisposable
{
  private bool disposed = false;

  //Implement IDisposable.
  public void Dispose()
  {
      Dispose(true);
      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);
  }
}

In the implementation of Dispose (), it calls GC.SupressFinalize (); but provides a destructor to complete the object.

What is the point of providing a destructor implementation when calling GC.SuppressFinalize ()?

Confuse a little, what are the intentions?

+4
source share
2 answers

There are 2 scenarios:

  • Your code calls are Dispose (preferred), and Finalizer is canceled, eliminating overhead.
  • Your code "leaks" the object, and the GC calls Finalizer.
+6
source

- Dispose, ( ) . , Dispose. .

+6

Source: https://habr.com/ru/post/1569714/


All Articles