Reputation: 864
I'm confused about this pattern.
If disposing is true(called from Dispose()) we free managed objects there. If disposing is false(called from Finalizer()) it is not safe to access referenced object, these referenced objects are the unmanaged objects like filestream.
If disposing is true then we won't be able to free unmanaged objects? If disposing is false we won't be able to free managed objects?
Searching this pattern, there has different implementation in Dispose(boolean) method. MSDN implementation
And this one I got from examples and tutorials.
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
// Free any other managed objects here.
}
else
{
//not safe to access referenced object
}
// Free any unmanaged objects here.
}
disposed = true;
}
Upvotes: 0
Views: 115
Reputation: 1994
In properly formed IDisposable
pattern true
value of disposing
implies that we reached the method from the explicit Dispose
call or by leaving using
scope which is preferable way of IDisposable
consumption. However not all consumers are properly implemented and in order to ensure that we are able to reclaim all unmanaged resources in the IDisposable
implementation we call Dispose(false)
from the finalizer. So false
in the Dispose
indicates that we reached this call at the finalization phase and some references can be unavailable at this stage that's why we use this flag - to distinguish what we can do under normal flow execution and what we can do under the finalization stage conditions. Unmanaged resources we deallocate regardless of this flag.
Upvotes: 1
Reputation: 7338
the clean up of unmanged resources must be done inside the method Dispose(boolean disposing)
regardless of the value of the parameter disposing
. You can find more details here
Upvotes: 1