WPF图像控制内存泄漏 [英] WPF Image control memory leak

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

问题描述

我的程序中有很多小图像(图像控件很小,而不是图像本身),说很多,我的意思是500多个.这些图像是异步生成的,然后分配给Image控件,这些控件之前已初始化.
基本上我的代码执行以下操作:

My program has a lot of small images (Image controls are small, not the images themselves) and by saying a lot I mean more than 500. These images are generated asynchronously and then assigned to the Image controls, which were initialized before.
Basically my code does the following:

            filename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, string.Format("{0}.JPG", Guid.NewGuid().GetHashCode().ToString("x2")));
            converter.ConvertPdfPageToImage(filename, i);
            //Fire the ThumbnailCreated event
            onThumbnailCreated(filename, (i - 1));  

创建图像的代码中没有内存泄漏,我有以下代码:

There is no memory leak in code that creates the images, I have the following code:

            string[] files = Directory.GetFiles("C:\\Users\\Daniel\\Pictures", "*.jpg");
            for(int i=0; i<files.Length; i++){
                onThumbnailCreated(files[i], i);
            } 

问题仍然存在. 这是在事件处理程序方法中发生的:

Still the problem persists. This happens in the event handler method:

    void Thumbnails_ThumbnailCreated(ThumbnailCreatedEventArgs e, object sender)
    {
        //Since we generate the images async, we need to use Invoke
        this.parent.Dispatcher.Invoke(new SetImageDelegate(SetImage), e.Filename, e.PageNumber);
    }

    private void SetImage(string filename, int pageNumber)
    {
        BitmapImage bitmap = new BitmapImage();
        bitmap.BeginInit();
        //I am trying to make the Image control use as less memory as possible
        //so I prevent caching
        bitmap.CacheOption = BitmapCacheOption.None;
        bitmap.UriSource = new Uri(filename);
        bitmap.EndInit();
        //We set the bitmap as the source for the Image control
        //and show it to the user
        this.images[pageNumber].Source = bitmap;
    }

使用468张图像,该程序使用大约1Gb的内存,然后完全用光.使用WPF是否可以实现我的任务,还是图像数量过多?我的代码可能有问题吗?
预先感谢

With 468 images the program uses about 1Gb of memory and then runs out of it at all. Is my task even possible to achieve using WPF or is the number of images too high? Maybe there is something wrong with my code?
Thanks in advance

推荐答案

您应

You should freeze these images and set their width (or height) to that will be actually used in the application if possible:

// ...
bitmap.DecodePixelWidth = 64; // "displayed" width, this improves memory usage
bitmap.EndInit();

bitmap.Freeze();
this.images[pageNumber].Source = bitmap;

这篇关于WPF图像控制内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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