Search code examples
c#.netgarbage-collectiondestructorfinalizer

Why isn't my .net destructor called in this very simple scenario?


I've got the following code :

 public class A
    {
        ~A()
        {
            Console.WriteLine("destructor");
        }
    }

 public static A Aref;
 static void Main(string[] args)
    {
        Aref = new A();
        int gen = GC.GetGeneration(Aref);
        Aref = null;
        GC.Collect(gen, GCCollectionMode.Forced);
        Console.WriteLine("GC done");

    }

I thought my Finalizer method would be called upon my call to GC.Collect, which is not the case.

Can anyone explain me why ?


Solution

  • Finalizers aren't called before GC.Collect() returns. The finalizers are run in a separate thread - you can wait for them by calling GC.WaitForPendingFinalizers().