Search code examples
c#multithreadinggarbage-collectionfinalizer

C#: dynamically check if the finalizer thread is blocked


I want to check if one finalizer method caused the finalizer thread to hang forever: is the finalizer thread in a blocked state (like a deadlock) or not.

If there are variations in different CLRs, I'm focused on standard .NET framework for Windows in versions higher than (say) 4.5.

I wrote the following code testing if a dummy object gets finalized. I assume:

  • there is only one finalizer thread (is it correct ?)
  • all finalizers run on the finalizer thread (is it correct ?)

Dummy object:

    /// <summary>
    /// Little class to test if the finalizer thread is alive. 
    /// Just runs an action when finalized
    /// </summary>
    private class DummyObject
    {
        /// <summary>
        /// Action to run when finalized
        /// </summary>
        private Action Finalized;

        /// <summary>
        /// Constructor
        /// </summary>
        public DummyObject(Action finalized)
        {
            Finalized = finalized;
        }

        /// <summary>
        /// Finalizer
        /// </summary>
        ~DummyObject()
        {
            Finalized();
        }
    }

Main code:

            bool finalized = false;
            var obj = new DummyObject(() => finalized = true);
            obj = null;
            GC.Collect();
            Thread.Sleep(1000);
            Console.Write("Finalizer thread is alive: " + finalized);

The exact question is: If this code displays true, does this prove the finalizer thread is not blocked?


Solution

  • If you really, really need such a self-diagnostic, I would rather not rely on such implementation details (although now - quite correct). I would rather write logic of self-checking FinalizersStart and FinalizersStop ETW/LLTng events being emitted. You can do it easily with the help of the TraceEvent library.