我打破了我的头,但我仍然努力获得解决方案。我运行这些代码并使用.NET内存分析器进行分析。它向我展示了IntEntity []的一个实例未被收集。但是我正在清除列表并将其设置为空。我如何使这个垃圾收集?我在这里做错了什么?c#内存泄漏分析
编辑:我试着设置b = null &调用GC.Collect(GC.MaxGeneration);但相同的结果。
编辑2:添加图像从NET内存分析器&蚂蚁内存分析器
请帮助我。
下面是代码正在使用,
public class IntEntity
{
public int Value { get; set; }
}
public abstract class Base
{
protected List<IntEntity> numbers;
public Base()
{
}
public abstract void Populate();
public int Sum()
{
numbers = new List<IntEntity>();
Populate();
int sum = 0;
foreach (IntEntity number in numbers)
{
sum += number.Value;
}
numbers.Clear();
numbers = null;
return sum;
}
}
public class Child : Base
{
public override void Populate()
{
numbers.Add(new IntEntity() { Value = 10 });
numbers.Add(new IntEntity() { Value = 20 });
numbers.Add(new IntEntity() { Value = 30 });
numbers.Add(new IntEntity() { Value = 40 });
}
}
Base b = new Child();
MessageBox.Show(b.Sum().ToString());
b = null;
GC.Collect(GC.MaxGeneration);
因为这里的'Base'类是抽象的,所以必须有一些其他代码需要诊断,是吗? – 2010-09-27 17:13:47
没有必要调用'numbers.Clear()'。只要设置'numbers = null',将会在下一次垃圾收集器完成它的事情时,收集清单并删除'IntEntity'引用。 – 2010-09-27 17:18:25
您的示例中缺少的代码中必须有其他内容。 – 2010-09-27 17:18:55