0

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.

(github repo of source)

Gábor Plesz
  • 1,203
  • 1
  • 17
  • 28
  • +1 Thank you @hans-passant! Unfortunately, I did not find the question, the point I was looking for this. Jitter+Debug build. Thank you! – Gábor Plesz Jan 20 '15 at 13:04

1 Answers1

0

You are expecting the wrong thing from garbage collection.

Stating your points:

If max=1, the finalizers run only after pressing the enter key, before exiting the program. Your for loop is run once, hence having a reference to GCInherited with 0 as number. Since the garbage collection is called within your program, there this is a reference to that object in inherited.

If max=2, the finalizers of 0 run before the enter (as expected), and finalizers of 1 run only after the enter. The same thign happens here, except the fact taht the first reference to GCInherited with number 0 is lost since you have overwritten it by initializing a new GCInherited with number 1 and write it to inherited.

If uncomment inherited=null, all finalizers run before pressing the enter key. Of course since there is no more reference to any of your GcInherited objects.

Xeun
  • 1,089
  • 1
  • 11
  • 20
  • Thanks for your answer! If i run the app, run the finalizers as expected, so the reason I did not know, **the jitter and the debug build**, as the as described in the referenced reply. – Gábor Plesz Jan 20 '15 at 13:21
  • sorry, i missed the 'release' word: if i run the app **with release config...** – Gábor Plesz Jan 20 '15 at 16:10