数组中的对象不会被垃圾收集

Pau*_*ley 6 .net c# garbage-collection

我正在测试一个使用弱引用的类,以确保对象能够被垃圾收集,并且我发现即使列表不再被引用,List <>中的对象也从未被收集过.简单数组也是如此.以下代码段显示了一个失败的简单测试.

class TestDestructor
{
    public static bool DestructorCalled;

    ~TestDestructor()
    {
        DestructorCalled = true;
    }
}

[Test]
public void TestGarbageCollection()
{
    TestDestructor testDestructor = new TestDestructor();

    var array = new object[] { testDestructor };
    array = null;

    testDestructor = null;

    GC.Collect();
    GC.WaitForPendingFinalizers();

    Assert.IsTrue(TestDestructor.DestructorCalled);
}
Run Code Online (Sandbox Code Playgroud)

省略阵列的初始化会导致测试通过.

为什么数组中的对象没有被垃圾收集?

Job*_*obo 2

另一个编辑:如果数组在 Main()-Method-Scope 中定义,则结果将始终为 false,但如果在 Class-Test-Scope 中定义,结果将始终为 true。也许这并不是一件坏事。

class TestDestructor
{
    public TestDestructor()
    {
        testList = new List<string>();
    }

    public static volatile bool DestructorCalled;

    ~TestDestructor()
    {
        DestructorCalled = true;
    }

    public string xy = "test";

    public List<string> testList;

}

class Test
{
    private static object[] myArray;

    static void Main()
    {
        NewMethod();            
        myArray = null;

        GC.Collect();
        GC.WaitForPendingFinalizers();
        Console.WriteLine(TestDestructor.DestructorCalled);
        Console.In.ReadToEnd();
    }

    private static void NewMethod()
    {
        TestDestructor testDestructor = new TestDestructor() { xy = "foo" };
        testDestructor.testList.Add("bar");
        myArray = new object[] { testDestructor };
        Console.WriteLine(myArray.Length);
    }
}
Run Code Online (Sandbox Code Playgroud)