I've got the following code :
public class A
{
~A()
{
Console.WriteLine("destructor");
}
}
public static A Aref;
static void Main(string[] args)
{
Aref = new A();
int gen = GC.GetGeneration(Aref);
Aref = null;
GC.Collect(gen, GCCollectionMode.Forced);
Console.WriteLine("GC done");
}
I thought my Finalizer method would be called upon my call to GC.Collect, which is not the case.
Can anyone explain me why ?
Finalizers aren't called before GC.Collect() returns. The finalizers are run in a separate thread - you can wait for them by calling GC.WaitForPendingFinalizers().
The finalizer is not called during the collection in your example, cause it is still being rooted by the finalizable queue. It is however scheduled for finalization, which means that it will be collected during the next garbage collection.
If you want to make sure instances of types with a finalizer are collected you need to do two collections like this.
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
But generally you should not call the Collect() method yourself.
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