4

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?

4

2 回答 2

6

有2种情况:

  • 您的代码调用 Dispose(首选)并取消终结器,从而消除开销。
  • 您的代码“泄漏”对象并且 GC 调用终结器。
于 2010-11-16T11:50:03.177 回答
6

如果有人忘记调用 Dispose,终结器将(最终)运行以进行最终清理。由于最终确定会损害性能,因此理想情况下没有人会忘记 Dispose。using 构造对此有所帮助。

于 2010-11-16T11:49:05.363 回答