Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

As following example implementation i.e. https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/implementing-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?

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

Is that implementation still correct?

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

        if (disposing)
        {
            if (this.cache != null)
            {
                this.cache.Dispose();
            }
        }            
    }
}
like image 272
ziomyslaw Avatar asked Dec 06 '25 04:12

ziomyslaw


1 Answers

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?

There are two flags in the pattern: disposing and disposed.

disposed starts false and is set to true as soon as the object is disposed. The purpose of disposed is to make Dispose idempotent. That is: it should always be legal to call Dispose twice, and the second time it should do nothing.

The protected Dispose(bool) method in the pattern has two callers: the regular Dispose method, and the finalizer. The pattern is that Dispose calls Dispose(true) and the finalizer calls Dispose(false) so that the implementation of the method knows whether to use normal rules or finalizer rules for cleaning up.

like image 180
Eric Lippert Avatar answered Dec 07 '25 20:12

Eric Lippert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!