Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/329.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为什么不是';在这个非常简单的场景中,我的.net析构函数调用了什么?_C#_.net_Garbage Collection_Destructor_Finalizer - Fatal编程技术网

C# 为什么不是';在这个非常简单的场景中,我的.net析构函数调用了什么?

C# 为什么不是';在这个非常简单的场景中,我的.net析构函数调用了什么?,c#,.net,garbage-collection,destructor,finalizer,C#,.net,Garbage Collection,Destructor,Finalizer,我有以下代码: public class A { ~A() { Console.WriteLine("destructor"); } } public static A Aref; static void Main(string[] args) { Aref = new A(); int gen = GC.GetGeneration(Aref);

我有以下代码:

 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");

    }
我以为我的Finalizer方法会在调用GC.Collect时被调用,但事实并非如此


有人能解释一下原因吗?

GC.Collect()返回之前没有调用终结器。终结器在单独的线程中运行-您可以通过调用
GC.WaitForPendingFinalizers()

来等待它们。在您的示例中,在收集过程中不会调用终结器,因为它仍由可终结队列作为根。但是,它被安排为最终完成,这意味着它将在下一次垃圾收集期间被收集

如果要确保收集带有终结器的类型实例,则需要进行两次这样的收集

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

但是通常您不应该自己调用
Collect()
方法

即使您要求GC收集,也不确定该特定对象是否会被销毁(因为它不可能在此时收集的生成中)

在这个简单的示例中,OP确保收集相关生成。因此,除非在显式调用Collect()之前有一个集合,否则它应该按预期工作。为什么需要第二个集合?通过运行终结器来收集任何符合条件的对象。类型具有终结器。在终结器运行或被抑制之前,实例将由终结器队列作为根。