Why is the traditional Dispose template submission complete?

Assuming this as a traditional Dispose pattern (taken from devx but seen on many websites)

class Test : IDisposable
{
  private bool isDisposed = false;

  ~Test()
  {
    Dispose(false);
  }

  protected void Dispose(bool disposing)
  {
    if (disposing)
    {
      // Code to dispose the managed resources of the class
    }

    // Code to dispose the un-managed resources of the class

    isDisposed = true;
  }

  public void Dispose()
  {
    Dispose(true);
    GC.SuppressFinalize(this);
  }
}

I do not understand why we call GC.SupressFinalize(this). Does this require me to write my own manageable disposition of resources, including nullifying my links? I must admit, I'm a little lost. Can someone shed light on this pattern?

Ideally, I would like to manage my unmanaged resources and let the GC do the managed collection on its own.

Actually, I don’t even know why we specify the finalizer. In any case, the encoder must call himself, right? If this is just a backup mechanism, I will remove it.

+5
source share
6

IDisposable , , Dispose .

, - Dispose.

Dispose, -- . SuppressFinalize , GC.

, : GC , , . , .

+8

SuppressFinalize .

GC.
. ( , )

, SuppressFinalize.

SuppressFinalize Dispose(false) GC . ( )

, . ( - SuppressFinalize, , ).

+2

SuppressFinalize , - . , ; , SuppressFinalize .

, , , , . ( , Finalize), , Queue Finalization. , , , , , - , , , . , ( ); , , ( , ) .

SuppressFinalize , , . souse (*), , ; . , , , , .

+2

Msdn: " , . obj . , IDisposable, IDisposable.Dispose, Object.Finalize , . "

, GC. finalizer, , , . GC , .

+2

As noted on MSDN, executing the Finalize method is expensive. By calling dispose, you have already finished your class, so the finalizer does not need to be called. The finalizer is implemented if Dispose is never called directly by your code (or whoever it is an "instance").

+1
source
// If the monitor.Dispose method is not called, the example displays the following output:
//       ConsoleMonitor instance....
//       The ConsoleMonitor class constructor.
//       The Write method.
//       The ConsoleMonitor finalizer.
//       The Dispose(False) method.
//       Disposing of unmanaged resources.
//       
// If the monitor.Dispose method is called, the example displays the following output:
//       ConsoleMonitor instance....
//       The ConsoleMonitor class constructor.
//       The Write method.
//       The Dispose method.
//       The Dispose(True) method.
//       Disposing of managed resources.
//       Disposing of unmanaged resources.

from https://msdn.microsoft.com/en-us/library/system.gc.suppressfinalize(v=vs.110).aspx

0
source

All Articles