I have a c# Console App (visual studio 2013 express), as follows:
class Program
{
static void Main(string[] args)
{
var max = 1;
for (int i = 0; i < max; i++)
{
var inherited = new GCInherited(i);
//you can not run, if I only create this class
//var gcbase = new GCBase(i);
//if explicit set to null, the finalizer started:
//inherited = null;
}
GC.Collect(2);
GC.WaitForPendingFinalizers();
//so do not run
//GC.WaitForFullGCApproach(-1);
//GC.WaitForFullGCComplete(-1);
Console.ReadLine();
}
}
class GCInherited : GCBase
{
public GCInherited(int nr) : base(nr) { }
~GCInherited() { Console.WriteLine("GCInherited finalizer ({0})", this.nr); }
}
class GCBase
{
public int nr { get; private set; }
public GCBase(int nr) { this.nr = nr; }
~GCBase() { Console.WriteLine("GCBase finalizer"); }
}
- If
max=1
, the finalizers run only after pressing the enter key, before exiting the program. - If
max=2
, the finalizers of 0 run before the enter (as expected), and finalizers of 1 run only after the enter. - If uncomment
inherited=null
, all finalizers run before pressing the enter key.
The question arises: WHY?
I would be very grateful for any idea.