IDisposable.Dispose() 会自动调用吗?

发布于 2024-11-28 09:07:27 字数 346 浏览 0 评论 0原文

可能的重复:
垃圾收集器会为我调用 IDisposable.Dispose 吗?

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

Possible Duplicate:
Will the Garbage Collector call IDisposable.Dispose for me?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

清风无影 2024-12-05 09:07:27

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

对于客户端来说,更好的方法是使用 using 语句来处理 Dispose() 的自动调用,即使存在异常也是如此。

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 方法)调用时,托管引用可能无效,因此只能释放非托管资源。

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.

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

A proper implementation of IDisposable is:

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); }
}

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.

北方。的韩爷 2024-12-05 09:07:27

如果您在 using 语句中实例化对象,则当代码退出 using 块时,系统会为您调用 Dispose()

using(var myObject = new MyDisposableObject())
{
  blah();
} // Dispose() is called here (or whenever the code exits the block)

如果您不使用 using >,然后由您(调用代码)通过显式调用 Dispose() 来处置您的对象。

另外,您(MyObject 的实现者)可以添加对终结器的支持,以防您的调用者不调用 Dispose()。更多信息请参见此处

If you instantiate your object in a using statement, Dispose() is called for you when code exits the using block

using(var myObject = new MyDisposableObject())
{
  blah();
} // Dispose() is called here (or whenever the code exits the block)

If you don't use using, then it's up to you (the calling code) to dispose of your object by explicitely calling Dispose().

Also, you (the implementor of MyObject) can add support for a finalizer in case your caller doesn't call Dispose(). More info here.

我很OK 2024-12-05 09:07:27

必须手动调用此方法,也许(假设“MyClass”实现“IDisposable”)在像

using(var myclass = new MyClass())
{
   // do something with myclass
}

// now 'myclass'is Disposed

C# 8.0这样的构造中,您可以编写如下语句:

using var myclass=new MyClass();

并且“myclass”将在范围末尾自动处理。

using 语句的优点(与显式调用 Dispose() 相比)是,无论您如何退出此块,都会调用 Dispose():通过运行到末尾,遇到 return 语句或抛出异常。

You will have to call this method manually, maybe (assuming that "MyClass" implements "IDisposable") in a construct like

using(var myclass = new MyClass())
{
   // do something with myclass
}

// now 'myclass'is Disposed

In C# 8.0, you can write as below statement:

using var myclass=new MyClass();

and the "myclass" will be disposed automatically at the end of the scope.

The advantage of the using statement (compared to calling Dispose() explicitly) is that Dispose() is called no matter how you exit this block: by running past the end, encountering a return statement or having an exception thrown.

江心雾 2024-12-05 09:07:27

为了确保资源被正确处置,您需要实现IDisposable并在析构函数(终结器)中调用Dispose

class Foo : IDisposable
{
    private bool m_disposed = false;

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

    ~Foo()
    {
        Dispose(false);
    }

    protected void Dispose(bool disposing)
    {
        if (!m_disposed)
        {
            if (disposing)
            { 
                //release managed resources
            }
            //release unmanaged resources

            m_disposed = true;
        }
    }
}

To make sure the resources are correctly disposed, you need to both implement IDisposable and call Dispose in the destructor(finalizer).

class Foo : IDisposable
{
    private bool m_disposed = false;

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

    ~Foo()
    {
        Dispose(false);
    }

    protected void Dispose(bool disposing)
    {
        if (!m_disposed)
        {
            if (disposing)
            { 
                //release managed resources
            }
            //release unmanaged resources

            m_disposed = true;
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文