2016-04-28 63 views
2

使用RemoveRange后,项目似乎保留在内存中。我对这些物品没有其他参考。我应该只使用一种解决方法,在其中复制我想要的项目并完全清除旧列表?c#列表<T> RemoveRange删除项目会发生什么?

打了个比方来说明:

private void Form1_Load(object sender, EventArgs e) 
{ 
    bmp = new Bitmap(5000, 5000, PixelFormat.Format32bppPArgb); 
    pictureBox1.Image = bmp; 
    pictureBox1.Width = bmp.Width;pictureBox1.Height = bmp.Height; 
    bmp2 = new Bitmap(some_image_file);//500x500 bitmap 
} 
private void pictureBox1_MouseDown(object sender, MouseEventArgs e) 
{ 
    bitmap_list.Add(new Bitmap(bmp)); 
    Graphics.FromImage(bmp).DrawImage(bmp2, e.X - bmp2.Width/2, e.Y - bmp2.Height/2); 
    pictureBox1.Refresh(); 
} 
private void button1_Click(object sender, EventArgs e) 
{// where do the items go? memory is not freed until running a manual GC 
    bitmap_list.RemoveRange(1, bitmap_list.Count - 1); 
} 
private void button2_Click(object sender, EventArgs e) 
{// if this is not clicked, memory will run out even after clearing the list 
    // down to one item 
    GC.Collect(); 
} 

谢谢!

回答

4

删除对象的最后一个引用不会将其销毁并释放内存,而是在垃圾收集器运行后的某个时间发生。

但是,由于您的物品是一次性的(例如,它们实施了IDisposable),因此您应该调用要删除的物品的Dispose(),例如在从列表中删除之前。这将让这些实例确定性地清理非托管资源,而不是等待GC和终结器运行,从而具有更像您预期的行为。

+0

谢谢,就是这样。我通常使用很多处置,但由于某种原因,在这里没有想到它。 – george

相关问题