mercredi 22 janvier 2020

C# destructor not called even after code scope + GC?

I've got a simple test code in Nunit+.net core 2.0 under VS2019:

public class Tests
{
    public static int i = 0;
    class First
    {
        ~First()
        {
            i += 1;
            Console.WriteLine("First's destructor is called.");
        }
    }

    class Second : First
    {
        ~Second() { i += 10; Console.WriteLine("Second's destructor is called."); }
    }

    class Third : Second
    {
        ~Third() { i += 100; Console.WriteLine("Third's destructor is called."); }
    }
    [Test]
    public static void Test()
    {
        {
            Third t = new Third();
        }
        Thread.Sleep(1000);
        System.GC.Collect();
        Assert.AreEqual(111, i);
    }
}

It always fails, while I found finally i=0, and the destructors are called right after Test(). But you can see the "t" is in a code block, and is invalid after the code block, and I also called

System.GC.Collect();

before my "Assert".

Why destructor is not called even after GC? How to fix my code to make the test pass?

Thanks a lot.

Aucun commentaire:

Enregistrer un commentaire