I always thought that the answer to this was no, but I cannot find any source stating this.
In my class below, can I access (managed) fields/properties of an instance of C
in the finalizer, i.e. in ReleaseUnmanaged()
? What restrictions, if any, are there? Will GC or finalization ever have set these members to null?
The only thing I can find is that stuff on the finalizer queue can be finalized in any order. So in that case, since the recommendation is that types should allow users to call Dispose()
more than once, why does the recommended pattern bother with a disposing
boolean
? What bad things might happen if my finalizer called Dispose(true)
instead of Dispose(false)
?
public class C : IDisposable
{
private void ReleaseUnmanaged() { }
private void ReleaseOtherDisposables() { }
protected virtual void Dispose(bool disposing)
{
ReleaseUnmanaged();
if (disposing)
{
ReleaseOtherDisposables();
}
}
~ C()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}