gpt4 book ai didi

c# List RemoveRange 删除的项目会发生什么?

转载 作者:行者123 更新时间:2023-11-30 20:36:28 25 4
gpt4 key购买 nike

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

谢谢!

最佳答案

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

但是,由于您的元素是一次性的(例如,它们实现了 IDisposable),您应该调用要移除的元素的 Dispose(),例如在移除之前从列表中。这将使实例确定性地清理非托管资源,而不是等待 GC 和终结器运行,从而使行为更像您预期的那样。

关于c# List<T> RemoveRange 删除的项目会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36926642/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com