情况:
>对象变得符合GC标准
> GC开始收集
> GC调用析构函数
>在析构函数中,例如,将当前对象添加到静态集合中
在收集对象的过程中,不符合GC的资格,将来会有资格,但在规范中说,Finalize只能被调用一次.
问题:
将对象摧毁?
将会在下一个GC上完成调用?
解决方法
该对象不会被垃圾回收 – 但是下一次它有资格进行垃圾收集时,终结器将不再运行,除非您调用
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(); } }
输出:
First collection... Finalizer count: 1 Second collection (nothing to collect) Third collection (cleared static variable) Finalizer count: 2 Fourth collection (no more finalization...)