9
- 對象就符合GC
- GC開始收集
- GC調用析構函數
- 在析構函數I,例如,添加當前對象的靜態集合
在收集對象的過程變得不適合GC,並且將來有資格,但是在規範中說Finalize只能調用一次。
問題:
- 會反對被破壞?
- 將敲定下一個GC嗎?
在收集對象的過程變得不適合GC,並且將來有資格,但是在規範中說Finalize只能調用一次。
問題:
對象將不被垃圾收集 - 但它是符合垃圾收集下一次,終結不會再次運行,除非你叫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...)
做.NET GC復活搜索,你會發現如[這篇文章](http://msdn.microsoft.com/en-us/magazine/bb985010.aspx) –