Is there a way to detect whether or not an object has called GC.SuppressFinalize?
I have an object that looks something like this (full-blown Dispose pattern elided for clarity):
public class ResourceWrapper {
private readonly bool _ownsResource;
private readonly UnmanagedResource _resource;
public ResourceWrapper(UnmanagedResource resource, bool ownsResource) {
_resource = resource;
_ownsResource = ownsResource;
if (!ownsResource)
GC.SuppressFinalize(this);
}
~ResourceWrapper() {
if (_ownsResource)
// clean up the unmanaged resource
}
}
If the ownsResource constructor parameter is false, then the finalizer will have nothing to do -- so it seems reasonable (if a bit quirky) to call GC.SuppressFinalize right from the constructor. However, because this behavior is quirky, I'm very tempted to note it in an XML doc comment... and if I'm tempted to comment it, then I ought to write a unit test for it.
But while System.GC has methods to set an object's finalizability (SuppressFinalize, ReRegisterForFinalize), I don't see any methods to get an object's finalizability. Is there any way to query whether GC.SuppressFinalize has been called on a given instance, short of buying Typemock or writing my own CLR host?
This is not possible, the GC just doesn't provide this information. Good reason for that, it isn't just two states that the object can be in. It also might already be on the finalization queue or it might already have been finalized.
A custom CLR host isn't going to help you with that, the hosting interface don't provide any hooks into the gc. You can check if SuppressFinalize has been called when it should have simply by checking this in the finalizer. Log it (quickly). You can't prove the opposite.
Fwiw, the .NET frame classes don't do this, they just let the finalizer run anyway.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With