Search code examples
c#debuggingfinalizer

Debugging objects failing to finalize?


I have the follow code in my application to help me check that ViewModels are being finalized correctly:

#if DEBUG
    static int openViewModels = 0;

    protected AbstractViewModel()
    {
        openViewModels++;
    }

    ~AbstractViewModel()
    {
        openViewModels--;
        System.Diagnostics.Debug.WriteLine(openViewModels);
    }
#endif

All viewModels in my application derive from this class. I find that over time, openViewModels increases, implying that some viewModels are failing to finalize.

I am having trouble working out why this is - I've stared at my code, but I can't see what is causing some objects to stay around. Is there any tools or procedures that can help me work out what is keeping these objects from being finalized?


Solution

  • Firstly, that is open to thread-race; that should be Interlocked.Increment(ref openViewModels) and Interlocked.Decrement(ref openViewModels).

    Secondly, finalization is non-deterministic. Unless you force it, which you shouldn't. You should not expect them to clean up in any particular time-scale, especially if you have a lot of memory available. Finalization is a factor of memory pressure.