We all know the System.IDisposable pattern. It's been described a zillion time, also here on StackOverflow:
link: Dispose() for cleaning up managed resources?
The Disposable patterns advises that I should only dispose managed resources if my object is being disposed, not during finalize
You can see that this happens because the following code is advised:
protected void Dispose(bool disposing)
{
if (disposing)
{
// Code to dispose the managed resources of the class
}
// Code to dispose the un-managed resources of the class
}
I know that my class should implement System.IDisposable whenever my class has a (private) member that implements System.IDisposable. The Dispose(bool) should call the Dispose() of the private member if the boolean disposing is true.
Why would it be a problem if the Dispose would be called during a finalize? So why would the following Dispose be a problem if it is called during finalize?
protected void Dispose(bool disposing)
{
if (myDisposableObject != null)
{
myDisposableObject.Dispose();
myDisposableObject = null;
}
}
myDisposableObject != null
check isn't enough, since you're in a multi-threaded environment - the reference could be nulled out between the check and theDispose
call. And finally, it's quite likely the finalizer on that object has also been scheduled (and perhaps even finished) already, so it's disposing work is probably done on both the managed and unmanaged side. – CarleencarlenDispose
on another managed object is meddling where you're not supposed to. Don't do that. – CarleencarlenFinalize()
method". Looks strange? But this is the way it works, and in CIL code try catch block finally is inserted to ensure base classes'Finalize()
execution, but only preventing user code mistakes. – FishbackFinalize()
method. If so, the object is marked as finalizable, and a pointer to this object is stored on an internal queue named the finalization queue". ... – FishbackFinalize()
method for each object on the freachable table at the next garbage collection. Given this, it will take at the very least two garbage collections to truly finalize an object." – Fishback