Alex
Alex

Reputation: 12039

IDisposable pattern: shall I annulate vars when GC.SupressFinalizer

Whenever I call GC.SupressFinalizer() in the Dispose method, should I assign null to all instance members to have them cleaned up, or they would be removed in any case ?

For example:

class test : IDisposable
{ 
    public int a = 10;
    public int b = 20;
    public int c = 39;

    private bool is_disposed = false;

    Dispose(bool shall_dispose)
    {
        if(!is_disposed && shall_dispose)
        {
            is_disposed = true;

            // shall I annulate a, b & c or they will be freed anyway??
            // a = null; ?, integers aint nullable 
            // b = null; ?
            // c = null; ?

            // or primitive types should't be annulated? only reference(heap) types?
        }
    }

    Dispose()
    {
        Dispose(true);
    }

    ~test()
    {
        Dispose(false);
    }
}

Upvotes: 0

Views: 75

Answers (2)

supercat
supercat

Reputation: 81179

The purpose of IDisposable.Dispose is to notify an object that it won't be needed any more, and should tell other objects that they no longer need to do anything on its behalf (such as leave a file open, granting exclusive access to a block of memory, etc.) Most of the time, shortly after an object is Dispose'd, any references to it will be abandoned, the object will become eligible for garbage collection, and its holding references to other objects will not delay their garbage collection. Nonetheless, clearing out other references may be a good idea. It's entirely possible that a reference may remain to an object long after Dispose is called. Further, it's possible that the IDisposable object might have been around long enough to reach Generation 2 in the garbage collector, meaning that it could be awhile for the garbage collector even looks at it again. If it holds references to more-recently-created objects, setting its references to null may allow those objects to be collected sooner than they otherwise would.

Upvotes: 1

Eugen Rieck
Eugen Rieck

Reputation: 65284

GC.SupressFinalizer() will not stop your object from being collected when it is no longer reachable, it will just supress the call to the object's finalizer. So both your object and its members will be collected, no matter wether you assign null or not.

Upvotes: 2

Related Questions