终结器如何增加 C# 中对象的生命周期?

How finalizer increases the life of an object in C#?

我正在读一本关于 C# 内存管理的书,上面写着:

What’s important to understand is that a finalizer increases the life of an object. Because the finalization code also has to run, the .NET Framework keeps a reference to the object in a special finalization queue. An additional thread runs all the finalizers at a time deemed appropriate based on the execution context. This delays garbage collection for types that have a finalizer.

据我所知,终结器 运行 只会在垃圾回收时使用,而不是在它之前。那么,它怎么能延迟垃圾回收呢?

通过评论发布的 MSDN 链接和删除的答案,以下是整个过程的详细信息:

当(通过 GC)发现可终结对象已死亡时,其终结器将放入队列中,以便执行其清理操作,但对象本身会提升到下一代。因此,你必须等到该代发生的下一次垃圾回收(不一定是下一次垃圾回收)才能确定对象是否已被回收。

以下是演示相同内容的代码:

using System;
class Program
{
    static void CreateDestructorReferences()
    {
        for (int i = 0; i < 1000; i++)
            _ = new Destructor();
    }
    static void CreateWithoutDestructorReferences()
    {
        for (int i = 0; i < 1000; i++)
            _ = new WithoutDestructor();
    }
    static void Main(string[] args)
    {
        CreateDestructorReferences();
        DemoGCProcess("****Objects With Destructors*****");
        CreateWithoutDestructorReferences();
        DemoGCProcess("****Objects Without Destructors*****");
        Console.ReadLine();
    }

    private static void DemoGCProcess(string text)
    {
        Console.WriteLine(text);
        var memory = GC.GetTotalMemory(false);
        GC.Collect(0);
        GC.WaitForPendingFinalizers();
        var memory1 = GC.GetTotalMemory(false);
        Console.WriteLine("Memory freed on first Garbage Collection on Generation 0:" + (memory - memory1));
        GC.Collect(1);
        var memory2 = GC.GetTotalMemory(false);
        Console.WriteLine("Memory freed on second Garbage Collection on Generation 0 and Generation 1:" + (memory1 - memory2));
    }
}
class Destructor
{

    ~Destructor()
    {
        //Console.WriteLine("Destructor is called");
    }
}
class WithoutDestructor
{

}

这是上面程序的输出: