IDisposable.Dispose()是否自动调用? [英] Is IDisposable.Dispose() called automatically?

查看:381
本文介绍了IDisposable.Dispose()是否自动调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

我有一个包含一些非托管资源的类。我的类实现了 IDisposable 接口,并在 Dispose()方法中释放了非托管资源。我必须调用 Dispose()方法,还是会以某种方式自动调用它?垃圾收集器会调用它吗?

I have a Class which has some unmanaged resources. My class implements the IDisposable interface and releases the unmanaged resources in the Dispose() method. Do I have to call the Dispose() method or will it be automatically called somehow? Will the Garbage Collector call it?

推荐答案

Dispose()不会被自动调用。如果有 finalizer ,它将自动被调用。实现 IDisposable 为类的用户提供了一种提前释放资源的方式,而不是等待垃圾回收器。

Dispose() will not be called automatically. If there is a finalizer it will be called automatically. Implementing IDisposable provides a way for users of your class to release resources early, instead of waiting for the garbage collector.

客户端的首选方法是使用 using 语句,该语句可处理 Dispose()的自动调用

The preferable way for a client is to use the using statement which handles automatic calling of Dispose() even if there are exceptions.

IDisposable 的正确实现是:

class MyClass : IDisposable
{
  private bool disposed = false;

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

  protected virtual void Dispose(bool disposing)
  {
    if(!disposed)
    {
      if(disposing)
      {
        // Manual release of managed resources.
      }
      // Release unmanaged resources.
      disposed = true;
    }
  }

  ~MyClass() { Dispose(false); }
}

如果该类的用户调用 Dispose( )直接进行清理。如果对象被垃圾收集器捕获,它将调用 Dispose(false)进行清理。请注意,从终结器(〜MyClass 方法)调用时,托管引用可能无效,因此只能释放非托管资源。

If the user of the class calls Dispose() the cleanup takes place directly. If the object is catched by the garbage collector, it calls Dispose(false) to do the cleanup. Please note that when called from the finalizer (the ~MyClass method) managed references may be invalid, so only unmanaged resources can be released.

这篇关于IDisposable.Dispose()是否自动调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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