c# - Dispose(bool) 中的 disposed 标志到底是什么意思?

标签 c# design-patterns idisposable

如以下示例实现即 https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/implementing-dispose有一个标志指示冗余调用。在示例中,它始终位于 Dispose(bool disposing) 方法的最后一行。这是否意味着它表示所有内容都已处理或只是简单地保护方法执行一次运行?

private bool disposed = false; // To detect redundant calls

protected virtual void Dispose(bool disposing)
{
    if (!disposed)
    {
        if (disposing)
        {
            if (this.cache != null)
            {
                this.cache.Dispose();
            }
        }

        disposed = true;
    }
}

该实现仍然正确吗?

protected virtual void Dispose(bool disposing)
{
    if (!disposed)
    {
        disposed = true; 

        if (disposing)
        {
            if (this.cache != null)
            {
                this.cache.Dispose();
            }
        }            
    }
}

最佳答案

there is a flag indicating redundant calls. In examples it is always in last line in Dispose(bool disposing) method. Does it mean that it indicates that everything has been disposed or just simple protect the method execution to be run once?

模式中有两个标志:disposingdisposed

disposed 开始为 false,并在对象被释放后立即设置为 true。 disposed 的目的是使 Dispose 幂等。也就是说:两次调用 Dispose 应该始终是合法的,而第二次应该什么都不做。

模式中 protected Dispose(bool) 方法有两个调用者:常规的Dispose 方法和终结器。模式是 Dispose 调用 Dispose(true) 终结器调用 Dispose(false) 以便方法的实现知道是否使用用于清理的常规规则或终结器规则。

关于c# - Dispose(bool) 中的 disposed 标志到底是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48869026/

相关文章:

c# - System.DBNull 错误

c# - 从终结器访问不可终结的对象

c# - 告诉 FxCop 另一个方法正在调用 dispose

c# - .Net/C# 对象应该自己调用 Dispose() 吗?

c# - 如何使用 C# 使光标线跟随图表中的鼠标

c# - 用空格替换 Unicode 字符 "�"

java - 支持不同后端的数据库客户端设计

Azure 存储投票模式

design-patterns - 这是什么设计模式?

c# - 私有(private)无效处置( bool )?