winforms ImageList 的内存问题
我有一个 ImageList
,里面填充了图像,你猜对了。 这些图像作为位图
加载到数据集中的内存中。直到我将它们加载到ImageList
中时,内存的上升才不用担心。但当它们被添加到 ImageList 时,内存使用量就会猛增。 但最大的问题是当我必须重新加载图像列表时。我尝试对列表中的每个图像调用 dispose,但内存未释放。 这是我尝试清理内存的代码:
foreach (Image item in imageList.Images)
{
item.Dispose();
}
imageList.Images.Clear();
GC.Collect();
我做错了什么?
I have an ImageList
that is populated with, well you guessed it, images.
These images are loaded into memory in a dataset as a Bitmap
. Until I loaded them into the ImageList
the rise of memory is not worry. But when they are added to the ImageList
the memory usage sky rockets.
But the biggest problem is when I have to reload the list of images. I've tried to call dispose on every image on the list but the memory is not freed.
This is the code I tried to clean up the memory:
foreach (Image item in imageList.Images)
{
item.Dispose();
}
imageList.Images.Clear();
GC.Collect();
What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的处置代码不合适。迭代 Images 集合实际上为每个图像创建了一个新的位图。然后您立即再次处置。只需调用 Clear() 即可。
GC.Collect() 也不能产生任何效果,ImageList 类是本机 Windows 组件的包装器。它将图像存储在本机内存中,而不是垃圾收集的内存中。
最后但并非最不重要的一个真正的问题是:Windows 内存管理器并不按照您想象的方式工作。当它释放内存时,它不会缩小程序的虚拟内存大小。它只是将内存块标记为未使用并将其添加到空闲块列表中。准备好以后重新使用。只有在极少数情况下,释放的内存恰好跨越整个保留内存页集,才能缩小虚拟内存大小。这不是一个真正的问题。这是虚拟的。
Your dispose code is not appropriate. Iterating the Images collection actually creates a new bitmap for each image. Which you then immediately dispose again. Just call Clear().
GC.Collect() cannot have any effect either, the ImageList class is a wrapper around the native Windows component. Which stores the images in native memory, not garbage collected memory.
Last but not least your real issue: the Windows memory manager just doesn't work the way you think. It does not shrink the virtual memory size of the program when it frees memory. It simply marks the block of memory as unused and adds it to the list of free blocks. Ready to be re-used at a later time. Only in the very rare case where the freed memory happens to span the entire set of reserved memory pages can it shrink the virtual memory size. This is not a real problem. It's virtual.