c# - Dispose() 方法中 GC.SuppressFinalize(this) 的目的是什么?

标签 c# .net garbage-collection idisposable suppressfinalize

我有以下代码:

public void Dispose()
{
    if (_instance != null)
    {
        _instance = null;
        // Call GC.SupressFinalize to take this object off the finalization
        // queue and prevent finalization code for this object from
        // executing a second time.
        GC.SuppressFinalize(this);
    }
}

虽然有评论解释了那个与 GC 相关的调用的目的,但我仍然不明白为什么它在那里。

一旦所有实例不复存在,对象是否注定要进行垃圾回收,例如在 using block 中使用时?

这将发挥重要作用的用例场景是什么?

最佳答案

在实现处置模式时,您还可以向调用 Dispose() 的类添加终结器。这是为了确保 Dispose() 总是 被调用,即使客户端忘记调用它。

为了防止 dispose 方法运行两次(如果对象已经被释放),你添加了 GC.SuppressFinalize(this);。该文档提供了一个 sample :

class MyResource : IDisposable
{
    [...]

    // This destructor will run only if the Dispose method 
    // does not get called.
    ~MyResource()      
    {
        // Do not re-create Dispose clean-up code here.
        // Calling Dispose(false) is optimal in terms of
        // readability and maintainability.
        Dispose(false);
    }

    // Implement IDisposable.
    // Do not make this method virtual.
    // A derived class should not be able to override this method.
    public void Dispose()
    {
        Dispose(true);
        // This object will be cleaned up by the Dispose method.
        // Therefore, you should call GC.SupressFinalize to
        // take this object off the finalization queue 
        // and prevent finalization code for this object
        // from executing a second time.
        GC.SuppressFinalize(this);
    }

    private void Dispose(bool disposing)
    {
        // Check to see if Dispose has already been called.
        if(!this.disposed)
        {
            // If disposing equals true, dispose all managed 
            // and unmanaged resources.
            if(disposing)
            {
                // Dispose managed resources.
                component.Dispose();
            }

            // Call the appropriate methods to clean up 
            // unmanaged resources here.
            resource.Cleanup()          
        }
        disposed = true;         
    }
}

关于c# - Dispose() 方法中 GC.SuppressFinalize(this) 的目的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3038571/

相关文章:

c# - 从谷歌云存储下载总是不正确的散列

c# - 10以下的int值转换为字符串两位数

c# - 如何检查类型是否永远不是有效的泛型参数?

c# - 如何实现双向类?

java - 处理后将对象设置为 null 是一种好习惯吗?

java - 如何预测jvm垃圾收集

c# - ObjectDisposedException 使用 MD5 ComputeHash 时

c# - 绑定(bind) DataGridComboBoxColumn

c# - 如何使用 Visual Studio SDK 扩展提供 Intellisense 的信息?

java - JVM 垃圾收集器中的自适应大小调整