Is it right that in C# Destructor (Finalizer) you can not access managed members of your class? If it is true, why is it? What other C# finalizer restrictions you know?
Example:
class MyClass
{
private FileStream _fs;
private IntPtr _handle;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~MyClass()
{
Dispose(false);
}
private void Dispose(bool isDisposing)
{
if (isDisposing)
{
_fs.Dispose(); // Won't be accessed from destructor
}
//some way to release '_handle' - this happans anyway (Called by Dispose or by Destructor)
}
}
Yes, you shouldn't access other managed classes from the finalizer, or from Dispose
when that method is called by the finalizer. By the time an object's finalizer is executed, the state of any managed object it once referenced is indeterminate. They may still exist, may be awaiting finalization themselves, or may have already been garbage-collected. In addition, finalizers are run on a different thread.