简体   繁体   English

在C#中使用Dispose()的终结器

[英]Finalizers with Dispose() in C#

See the code sample from MSDN: ( http://msdn.microsoft.com/en-us/library/b1yfkh5e(v=VS.100).aspx ) 请参阅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. 在Dispose()实现中,它调用GC.SupressFinalize();,但提供了一个析构函数来完成对象。

What is the point of providing an implementation for the destructor when GC.SuppressFinalize() is called? 调用GC.SuppressFinalize()时为析构函数提供实现有什么意义?

Just little bit confused what the intentions are? 只是有点混淆意图是什么?

If someone forgets to call Dispose, the finalizer will (eventually) run to do final cleanup. 如果有人忘记调用Dispose,终结器将(最终)运行以进行最终清理。 Since finalization hurts performance, ideally no-one will forget to Dispose. 由于最终确定会损害性能,理想情况下没有人会忘记Dispose。 The using construct helps a little with that. 使用构造对此有所帮助。

There are 2 scenarios: 有两种情况:

  • Your code calls Dispose (preferred) and the Finalizer is canceled, eliminating the overhead. 您的代码调用Dispose(首选)并取消Finalizer,从而消除了开销。
  • Your code 'leaks' the object and the GC calls the Finalizer. 您的代码“泄漏”了对象,GC调用了Finalizer。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM