Can I detect whether an object has called GC.SuppressFinalize?
Posted
by
Joe White
on Stack Overflow
See other posts from Stack Overflow
or by Joe White
Published on 2011-01-08T15:50:08Z
Indexed on
2011/01/08
15:53 UTC
Read the original article
Hit count: 211
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?
© Stack Overflow or respective owner