Search code examples
c#destructorfinalization

Finalizer C#. Why Finalizer not calling?


Why is my finalizer not being called?

using System;

class Program
{
    static void Main(string[] args)
    {
        Test test = new Test();
    }
}

class Test
{
    public Test()
    {
        Console.WriteLine("Start");
    }   

    ~Test()
    {
        Console.WriteLine("End");
    }
}

I searched on the Internet, I did not find anything suitable. I was expecting a console output "End" at the end.


Solution

  • There's no requirement for all finalizers to be executed when the process terminates. Finalizers should not be used for things that absolutely must happen.

    You can call GC.WaitForPendingFinalizers() if you really want to - along with other GC. methods to prompt garbage collection in the first place - but doing so in production code is usually a sign of a problematic design. Finalizers just aren't designed to work this way. They should be extremely rare in C# code in general; in my experience they're usually used to log warnings of "You appear not to have disposed of this, and you really should do - clean up will happen eventually, but this is something that should be cleaned up more eagerly."