我打破了我的頭,但我仍然努力獲得解決方案。我運行這些代碼並使用.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