Reputation: 211
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();
}
}
}
}
Upvotes: 2
Views: 866
Reputation: 660573
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.
Upvotes: 9