c#List <t> RemoveRange删除项目会发生什么?

时间:2016-04-28 22:36:12

标签: c#

使用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();
}

谢谢!

1 个答案:

答案 0 :(得分:4)

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

但是,由于您的商品是一次性的(例如,他们实施Select distinct b.branch_id, b.branch_date CASE WHEN b.branch_id like L%' THEN TRIM(substr((TO_CHAR(TRIM(LEADING 0 FROM b.branch_id))),-10)) WHEN b.branch_id like ‘%BRANCH%' THEN substr(b.branch_loc,2,9) || substr(i.branch_name,1,9) END AS BRANCH_INFO from tbl_brach b JOIN tbl_branch_info i on b.branch_id = i.branch_id_key where b.branch_id like L%' ),您应该调用要删除的商品IDisposable,例如在从列表中删除之前。这将使实例确定性地清理非托管资源,而不是等待GC和终结器运行,从而使行为更像您期望的那样。