Situation:
In process of collection object becomes ineligible for GC, and will be eligible in future, but in specification said that Finalize can be called only once.
Questions:
The object will not be garbage collected - but next time it's eligible for garbage collection, the finalizer won't be run again, unless you call GC.ReRegisterForFinalize
.
Sample code:
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();
}
}
Output:
First collection...
Finalizer count: 1
Second collection (nothing to collect)
Third collection (cleared static variable)
Finalizer count: 2
Fourth collection (no more finalization...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With