在WPF中加载多个图像时防止内存膨胀 [英] Prevent Memory Bloat When Loading Multiple Images In WPF

查看:296
本文介绍了在WPF中加载多个图像时防止内存膨胀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的WPF应用程序,用于一次在一个图像中预览任何给定文件夹中的图像。您可以将其视为Windows Image Viewer克隆。如果按下左箭头键或右箭头键,该应用程序有一个PreviewKeyUp事件用于加载文件夹中的上一个或下一个图像。

I have a very simple WPF app which is used to preview images in any given folder one image at a time. You can think of it as a Windows Image Viewer clone. The app has a PreviewKeyUp event used to load the previous or next image in the folder if the left arrow or right arrow key is pressed.

<Grid>
    <Image x:Name="CurrentImage" />
</Grid>

private void Window_PreviewKeyUp(object sender, KeyEventArgs e)
{
    switch (e.Key)
    {
        case Key.Left:
            DecreaseIndex();
            break;
        case Key.Right:
            IncreaseIndex();
            break;
    }

    var currentFile = GetCurrentFile();
    CurrentImage.Source = new BitmapImage(new Uri(currentFile));
}

我想解决的问题是有大量的问题加载多个图像直到垃圾收集发生时内存膨胀。你可以在我对应用程序内存使用情况的截图中看到这一点。在垃圾收集发生之前它超过300 MB并不罕见。

The problem I'm trying to solve is that there is a large amount of memory bloat when loading multiple images until garbage collection occurs. You can see this in the screenshot I took of the app's memory usage. It's not uncommon for it to exceed 300 MB before garbage collection occurs.

我尝试在using语句中包装图像,但这不起作用,因为BitmapImage没有实现IDisposable。

I tried wrapping the image in a using statement, but that doesn't work because BitmapImage doesn't implement IDisposable.

using (var image = new BitmapImage(new Uri(currentFile)))
{
    CurrentImage.Source = image;
}

在将多个图像加载到我的应用程序中时,我该怎么做才能防止内存膨胀?

What can I do to prevent memory bloat when loading multiple images into my app?

推荐答案

在位图对象上调用 .Freeze(),这套它进入只读状态并释放它上面的一些句柄,阻止它进入GC。

Call .Freeze() on the bitmap object, this sets it in to a read-only state and releases some of the handles on it that prevents it from getting GC'ed.

你可以做的另一件事是你可以告诉它BitmapImage绕过缓存,你看到的内存可以来自缓存。

Another thing you can do is you can tell the BitmapImage to bypass caching, the memory you see building up could be from the cache.

CurrentImage.Source = new BitmapImage(new Uri(currentFile), 
                                   new RequestCachePolicy(RequestCacheLevel.BypassCache));

最后,如果计算机上没有运行大量程序,会给系统带来内存压力。只要它想要GC,就允许net等待。在GC期间执行GC很慢并降低性能,如果不需要GC,因为没有人请求ram,那么它不会执行GC。

Lastly, if there is not a lot of programs running on the computer putting memory pressure on the system .net is allowed to wait as long as it wants for a GC. Doing a GC is slow and lowers performance during the GC, if a GC is not necessary because no one is requesting the ram then it does not do a GC.

这篇关于在WPF中加载多个图像时防止内存膨胀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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