情况:
在收集过程中,对象变得不符合GC的条件,并且将来有资格使用,但在规范中说Finalize只能调用一次。
问题:
答案 0 :(得分:12)
该对象将不被垃圾收集 - 但下次有资格进行垃圾收集时,终结者将不再再次运行,除非您致电{{3} }。
示例代码:
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();
}
}
输出:
First collection...
Finalizer count: 1
Second collection (nothing to collect)
Third collection (cleared static variable)
Finalizer count: 2
Fourth collection (no more finalization...)