December 2, 2007

Pattern for Detecting Object Leaks

A simple method
// Add these to the class
private static int instanceId = 1;
private int instance = 1;

// Call this within the contructor
public SetObjectInstance(...)
{
    instance = instanceId;
    instanceId++;
    Debug.WriteLine("XXX instance \'" +
        instance.ToString() + "\' constructed");
}

// Within the finalizer OR if the object does not have a Finalizer add one
~XXX()
{
    Debug.WriteLine("XXX instance \'" + instance.ToString() + 
     "\' finalized");
}

No comments: