如果在析构函数中我创建一个对象的活动引用怎么办?

Ole*_*ilo 9 .net c#

情况:

  1. 对象符合GC的条件
  2. GC开始收集
  3. GC调用析构函数
  4. 例如,在析构函数I中,将当前对象添加到静态集合中

在收集过程中,对象变得不符合GC的条件,并且将来有资格,但在规范中说Finalize只能被调用一次.

问题:

  1. 会被摧毁吗?
  2. 最终将在下一次GC上调用吗?

Jon*_*eet 12

该对象不会被垃圾收集 - 但下次它有资格进行垃圾收集时,除非你打电话,否则终结器不会再次运行GC.ReRegisterForFinalize.

示例代码:

using System;

class Test
{
    static Test test;

    private int count = 0;

    ~Test()
    {
        count++;
        Console.WriteLine("Finalizer count: {0}", count);
        if (count == 1)
        {
            GC.ReRegisterForFinalize(this);
        }
        test = this;
    }

    static void Main()
    {
        new Test();
        Console.WriteLine("First collection...");
        GC.Collect();
        GC.WaitForPendingFinalizers();

        Console.WriteLine("Second collection (nothing to collect)");
        GC.Collect();
        GC.WaitForPendingFinalizers();

        Test.test = null;
        Console.WriteLine("Third collection (cleared static variable)");
        GC.Collect();
        GC.WaitForPendingFinalizers();

        Test.test = null;
        Console.WriteLine("Fourth collection (no more finalization...)");
        GC.Collect();
        GC.WaitForPendingFinalizers();
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

First collection...
Finalizer count: 1
Second collection (nothing to collect)
Third collection (cleared static variable)
Finalizer count: 2
Fourth collection (no more finalization...)
Run Code Online (Sandbox Code Playgroud)