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

拥有回忆 提交于 2019-12-11 02:33:42

问题


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 ?


回答1:


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().




回答2:


The finalizer is not called during the collection in your example, cause it is still being rooted by the finalizable queue. It is however scheduled for finalization, which means that it will be collected during the next garbage collection.

If you want to make sure instances of types with a finalizer are collected you need to do two collections like this.

GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();

But generally you should not call the Collect() method yourself.




回答3:


Even if you ask for the GC to collect, it is unsure that this specific object will be destroyed (as it could not be in the generation being collected at that moment)



来源:https://stackoverflow.com/questions/606524/why-isnt-my-net-destructor-called-in-this-very-simple-scenario

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!