lundi 19 février 2018

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

As following example implementation i.e. https://docs.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();
            }
        }            
    }
}

Aucun commentaire:

Enregistrer un commentaire