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

What exactly does the disposed flag mean in Dispose(bool)?

作为以下示例实现,即 https://docs.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 两次应该总是合法的,而第二次应该什么都不做。

模式中受保护的 Dispose(bool) 方法有两个调用者:常规 Dispose 方法和终结器。模式是 Dispose 调用 Dispose(true) 终结器调用 Dispose(false) 以便该方法的实现知道是使用普通规则还是终结器规则进行清理。