2010-09-27 140 views
1

我打破了我的头,但我仍然努力获得解决方案。我运行这些代码并使用.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); 

alt text

alt text

+1

因为这里的'Base'类是抽象的,所以必须有一些其他代码需要诊断,是吗? – 2010-09-27 17:13:47

+1

没有必要调用'numbers.Clear()'。只要设置'numbers = null',将会在下一次垃圾收集器完成它的事情时,收集清单并删除'IntEntity'引用。 – 2010-09-27 17:18:25

+1

您的示例中缺少的代码中必须有其他内容。 – 2010-09-27 17:18:55

回答

1

吉姆米歇和史蒂芬Sudit指出,这可能是GC可能根本不会被收集,因为RAM可用于运行时大于程序所需的内存量

您可以添加GC。将数字设置为空后收集(),它可能会从您的配置文件中消失。

你应该注意到,通常你只应该为了测试目的而引发一个垃圾收集。

+0

“你应该注意到,通常你只应该为了测试目的而引发一个垃圾收集”......为什么? – Jason 2010-09-27 17:38:28

+1

由于微软花费了大量的时间搞清楚GC运行的时间,并且它做得非常好。 – Bryan 2010-09-27 17:41:51