问题描述
我是测试,使用弱引用,以保证对象能够被垃圾回收的一类,我发现,在一个名单,其中的对象;>从来没有收集即使列表不再被引用。这也是用一个简单的阵列的情况。下面code片段展示了一个简单的测试失败。
I was testing a class that uses weak references to ensure that objects were able to be garbage collected and I found that objects in a List<> were never collected even if the list is no longer referenced. This is also the case with a simple array. The following code snippet shows a simple test that fails.
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);
}
离开出数组的初始化使测试通过
Leaving out the initialisation of the array causes the test to pass.
为什么在数组中的对象没有得到垃圾回收?
Why is the object in the array not getting garbage collected?
推荐答案
另一个编辑:结果将始终为false,如果阵列中的Main()中定义的 - 方法,适用范围,但如果在讲座中定义为真测试范围。也许那不是一件坏事。
Another edit: result will be always false if the array is defined in the Main()-Method-Scope, but will be true if defined in the Class-Test-Scope. Maybe thats not a bad thing.
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);
}
}
这篇关于在数组中的对象没有得到垃圾回收的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!