Can I tell if an object called GC.SuppressFinalize?

Is there a way to determine if an object called GC.SuppressFinalize?

I have an object that looks something like this (fullscreen Dispose template 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 constructor parameter ownsResourceis equal false, then the finalizer has nothing to do - so it seems reasonable (if a little bizarre) to call GC.SuppressFinalizedirectly from the constructor. However, since this behavior is quirky, I will very tempting to notice it in the comments on the XML document ... and if I want to comment on it, then I have to write a unit test for it.

System.GC (SuppressFinalize, ReRegisterForFinalize), - . , GC.SuppressFinalize , Typemock CLR?

+3
3

, , , , , ? GC.Collect GC.WaitForPendingFinalizers, , ( ). : , , , .

, , ResourceWrapper OwnedResourceWrapper SharedResourceWrapper, . , , . , SharedResourceWrapper IDisposable no-op.

+3

, GC . , . .

CLR , gc. , SuppressFinalize, . (). .

Fwiw, .NET , .

+4

It may help (reductio absurdum). The trick would be to do some kind of log (it could be a static state) in the finalizers, and if someone is absent, it will cause completion to complete, but still you cannot be sure when.

This works if you are an author of this type.

+2
source

Source: https://habr.com/ru/post/1784269/


All Articles