在列表框中的WPF中处理图像(内存泄漏) [英] Dispose of Image in WPF in Listbox (memory leak)

查看:91
本文介绍了在列表框中的WPF中处理图像(内存泄漏)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表框,其中有一堆图像(通过数据模板完成).通过设置项目来源来创建图像:

I have a ListBox with a bunch of images in it (done through a datatemplate). The images are created by setting the items source:

<Image x:Name="ItemImage" Source="{Binding ImageUrl}"/> 

,然后使用列表框的Items.Clear()方法清除它们.通过使用列表框的Items.Add方法添加新图像.

and then they are cleared by using the listbox's Items.Clear() method. New Images are added by using the Items.Add method of the listbox.

但是,内存使用量才刚刚开始上升.正在显示的是大约300张左右的小图像,但是似乎从未释放过内存.该应用程序开始使用约40Megs,并迅速攀升至700Megs.如何释放所有这些图像正在使用的内存?

However, memory usage just starts moving up and up and up. It is the same 300 or so small images that are getting displayed, but the memory never seems to get freed. The App starts using about 40Megs, and quickly climbs up to 700Megs. How do I free up the memory that all these images are using?

编辑:我忘记提及的一件事是,正在通过网络加载图像(每个图像的大小约为4-5k).缓存以某种方式负责吗?显示12张图像会消耗大约10 Meg的内存,这大约是文件大小的100倍.

EDIT: One thing I forgot to mention, the images (which are about 4-5k each in size) are being loaded over the network. Is caching somehow responsible for this? Displaying 12 Images chews up about 10 Megs of memory, which is about 100X filesize.

推荐答案

除非您在加载图像时做任何不寻常的事情(例如使用自制的图像加载器之类的东西),否则GC应该在没有引用它们的情况下为您清除它们不再.

Unless you are doing anything unusual when loading the images (like using homebrewed image loaders or something) then the GC should wipe them out for you when nothing is referencing them anymore.

您是否坚持在任何地方引用数据?请记住,事件和事件处理程序有时可能会欺骗"垃圾收集器,使其认为某个对象仍在使用中:

Are you holding on to references to the data anywhere? Remember that events and event handlers can sometimes "trick" the garbage collector into thinking that an object is still in use:

MyObject obj = new MyObject();
obj.TheEvent += new EventHandler(MyHandler);
obj = null;
// Now you might think that obj is set for collection but it 
// (probably - I don't have access to MS' .NET source code) isn't 
// since we're still listening to events from it.

不确定这是否适用于您,但是至少那是我要检查我是否是您的情况.

Not sure if this applies to you, but at least that's were I'd check if I were you.

此外,如果您有权使用分析器(例如AQTime或类似的工具),则通过它运行代码可能会给您一些提示.

Also, if you have access to a profiler, such as AQTime or similar, then running your code through it might give you some hints.

您还可以尝试查看从磁盘或嵌入到程序集中的资源中加载图像是否有任何作用.

You could also try and see if it makes any difference if you load images from disk or from resources embedded into your assembly.

这篇关于在列表框中的WPF中处理图像(内存泄漏)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆