Finalizers with Dispose() in C#

社会主义新天地 提交于 2019-11-30 18:26:35

问题


See the code sample 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 Dispose() implementation it calls GC.SupressFinalize();, but provide a destructor to finalise the object.

What is the point of providing an implementation for the destructor when GC.SuppressFinalize() is called?

Just little bit confused what the intentions are?


回答1:


There are 2 scenarios:

  • Your code calls Dispose (preferred) and the Finalizer is canceled, eliminating the overhead.
  • Your code 'leaks' the object and the GC calls the Finalizer.



回答2:


If someone forgets to call Dispose, the finalizer will (eventually) run to do final cleanup. Since finalization hurts performance, ideally no-one will forget to Dispose. The using construct helps a little with that.



来源:https://stackoverflow.com/questions/4193755/finalizers-with-dispose-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!