为什么传统的Dispose模式抑制最终完成? [英] Why does the traditional Dispose pattern suppress finalize?

查看:108
本文介绍了为什么传统的Dispose模式抑制最终完成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设这是传统的Dispose模式(来自devx,但在许多网站上都可以看到)

Assuming this as the 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);
  }
}

我不明白为什么我们叫GC.SupressFinalize(this).这需要我编写自己的托管资源处理方法,包括使引用无效吗?我必须承认,我有点迷茫.有人可以阐明这种模式吗?

I don't understand why we call GC.SupressFinalize(this). This requires me to write my own managed resource disposal, including nulling my references? I'm a bit lost, I must admit. Could someone shed some light on this pattern?

理想情况下,我只想处置我的非托管资源,然后让GC自己进行托管收集.

Ideally, I would like to only dispose my unmanaged resources and let the GC do the managed collecting by itself.

实际上,我什至不知道为什么要指定终结器.无论如何,编码员应该自己打电话处理,现在不是吗?如果那只是一个备用机制,我会删除它.

Actually, I don't even know why we specify a finalizer. In any case, the coder should call dispose himself, now shouldn't he? If that's just a fallback mechanism, I'd remove it.

推荐答案

使用IDisposable模式,以便在客户端代码调用Dispose方法时,该对象可以确定性地清理其资源.

The IDisposable pattern is used so that the object can clean up its resources deterministically, at the point when the Dispose method is called by the client code.

仅当客户端代码由于某些原因无法调用Dispose时,终结器才作为备用.

The finaliser is only there as a fallback in case the client code fails to call Dispose for some reason.

如果客户端代码调用Dispose,则将在该过程中反复进行资源清理,并且在完成过程中无需再次执行 .在这种情况下调用SuppressFinalize意味着该对象不再产生额外的GC最终确定成本.

If the client code calls Dispose then the clean-up of resources is performed there-and-then and doesn't need to be done again during finalisation. Calling SuppressFinalize in this situation means that the object no longer incurs the extra GC cost of finalisation.

并且,如果您自己的类仅使用 managed 资源,则完全不需要终结器:GC将处理所有托管资源,让那些资源本身担心是否使用它们需要一个后备终结器.如果直接处理非托管资源,则只应在自己的类中考虑终结器.

And, if your own class only uses managed resources then a finaliser is completely unnecessary: The GC will take care of any managed resources, let those resources themselves worry about whether they need a fallback finaliser. You should only consider a finaliser in your own class if it directly handles unmanaged resources.

这篇关于为什么传统的Dispose模式抑制最终完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆