具有自动内存清理功能的图像下载器 [英] Image downloader with auto memory cleaning

查看:23
本文介绍了具有自动内存清理功能的图像下载器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表(简单的列表框),其中包含主从基础上的图像(如果用户单击列表项,将打开详细信息页面).我遇到了非常著名的图像内存泄漏问题,在 here 中描述,此处这里此处.

I have a list (simple ListBox) of items with images on master-detail base (if user clicks on list item, details page is opened). I faced quite famous problem with images memory leaks, described here, here, here, and here.

一种可能的方法是遍历所有图像 当 NavigatingFrom 清理它们时.

One possible way is to run through all images when NavigatingFrom and clean them.

其中一个线程,我发现了更有趣的解决方案:它会自动清理图像,但这不适用于虚拟化(如果添加私有字段来存储 ImageSource,则图像会丢失或混合).建议的修复是添加依赖属性.

In one of the threads, i found more interesting solution: it cleans images automatically, but that is not working for virtualization (images are lost or mixed, if to add private field for storing ImageSource). Suggested fix was to add dependency property.

但我仍然面临同样的问题:向下滚动并返回后图像混淆了.看起来依赖属性是随机更改的,但我无法捕捉它们更改的时刻.

But i'm still facing the same problem: images are mixed up after scrolling down and returning up. Looking like dependency property are changed randomly, but i cant catch the moment when they are changing.

public class SafePicture : ContentControl
{
    public static readonly DependencyProperty SafePathProperty =
        DependencyProperty.RegisterAttached(
            "SafePath",
            typeof(string),
            typeof(SafePicture),
            new PropertyMetadata(OnSourceWithCustomRefererChanged));

    public string SafePath
    {
        get { return (string)GetValue(SafePathProperty); }
        set { SetValue(SafePathProperty, value); }
    }

    private static void OnSourceWithCustomRefererChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
    {
        if (e.NewValue == null) // New value here
            return;
    }


    public SafePicture()
    {
        Content = new Image();
        Loaded += OnLoaded;
        Unloaded += OnUnloaded;
    }

    private void OnLoaded(object _sender, RoutedEventArgs _routedEventArgs)
    {
        var image = Content as Image;

        if (image == null)
            return;

        var path = (string)GetValue(SafePathProperty); // Also, tried SafePath (debugger cant catch setter and getter calls), but same result.

        image.Source = null;
        {
            var request = WebRequest.Create(path) as HttpWebRequest;
            request.AllowReadStreamBuffering = true;
            request.BeginGetResponse(result =>
            {
                try
                {
                    Stream imageStream = request.EndGetResponse(result).GetResponseStream();
                    DispatcherHelper.CheckBeginInvokeOnUI(() =>
                    {
                        if (imageStream == null)
                        {
                            image.Source = new BitmapImage { UriSource = new Uri(path, UriKind.Relative) };
                            return;
                        }

                        var bitmapImage = new BitmapImage();
                        bitmapImage.CreateOptions = BitmapCreateOptions.BackgroundCreation;
                        bitmapImage.SetSource(imageStream);
                        image.Source = bitmapImage;
                    });
                }
                catch (WebException)
                {
                }
            }, null);
        }
    }


    private void OnUnloaded(object sender, RoutedEventArgs e)
    {
        var image = Content as Image;

        if (image == null)
            return;

        var bitmapImage = image.Source as BitmapImage;
        if (bitmapImage != null)
            bitmapImage.UriSource = null;
        image.Source = null;
    }
}

用法:

<wpExtensions:SafePicture SafePath="{Binding ImageUrl}"/>

所以,乍一看,它工作正常,但如果向下滚动并向上返回,图像会随机更改.

So, at first glance, it works fine, but if to scroll down and return up, images are changed randomly.

在这种情况下,目前,我只使用纯 ListBox,没有虚拟化(但在其他情况下期待它).

in this case, for now, i'm using only pure ListBox, without virtualization (but expecting it in other cases).

重现此问题的示例项目.我相信,它会在一段时间内包含解决方案:https://simca.codeplex.com/

sample project to reproduce this problem. I believe, it would contain solution in a while: https://simca.codeplex.com/

推荐答案

问题在于,当使用虚拟化时,用于每个项目的 ui 元素被回收并重新用于其他对象(因此包括图像对象),并且由于您当您滚动得足够快时,正在异步加载图像,您将在图像上设置一个位图,该位图已被用于另一个项目.
快速修复只是检查路径值是否仍然相同,如果不是,则返回,因为该图像已被另一个对象重用:

The problem is that when using virtualisation, the ui element used for each item are recycled and reused for other object (so that include the image object) and since you are loading the image asynchronously when you scroll fast enough your will be setting a Bitmap on an Image which are already been reused for another item.
A quick fix for is just to check that the path value is still the same and if it is not, just return since the image has already been reused for another object:

...
var request = WebRequest.Create(path) as HttpWebRequest;
        request.AllowReadStreamBuffering = true;
        request.BeginGetResponse(result =>
        {

            try
            {

                Stream imageStream = request.EndGetResponse(result).GetResponseStream();
                DispatcherHelper.CheckBeginInvokeOnUI(() =>
                {
                if (path!=SafePath){
                  //Item has been recycled
                  return;
                }
                 ....

代码中有几个问题:- 将 RegisterAttached 切换为 Register,RegisterAttached 用于附加属性而不是正常的依赖属性- 在 OnSourceWithCustomRefererChanged 中调用 OnLoaded 因为 SafePath 属性更改实际上可以在元素加载后发生-在onLoaded的开头添加清晰的uri和source,以便path为空时清晰图像

There were a several problem in the code: -Switch RegisterAttached to Register, RegisterAttached is for attached property not normal dependency property -call OnLoaded in OnSourceWithCustomRefererChanged because the SafePath property changed can actually happpen after the element is loaded -Add clear uri and source at the start of onLoaded so that it clear image when path is empty

这是一个完整的工作代码:

Here is a full working code :

public class SafeImage : ContentControl
{
    private SynchronizationContext uiThread;

    public static readonly DependencyProperty SafePathProperty =
        DependencyProperty.Register("SafePath", typeof (string), typeof (SafeImage),
        new PropertyMetadata(default(string), OnSourceWithCustomRefererChanged));

    public string SafePath
    {
        get { return (string) GetValue(SafePathProperty); }
        set { SetValue(SafePathProperty, value); }
    }


    private static void OnSourceWithCustomRefererChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
    {
        SafeImage safeImage = o as SafeImage;
        safeImage.OnLoaded(null, null);
        //OnLoaded(null, null);
        if (e.NewValue == null)
            return;
    }





    public SafeImage()
    {
        Content = new Image();
        uiThread = SynchronizationContext.Current;

        Loaded += OnLoaded;
        Unloaded += OnUnloaded;
    }

    private void OnLoaded(object _sender, RoutedEventArgs _routedEventArgs)
    {
        var image = Content as Image;

        if (image == null)
            return;

        var path = SafePath; //(string)GetValue(SafePathProperty);
        //image.Source = new BitmapImage(new Uri(SafePath));
        Debug.WriteLine(path);

        var bitmapImage = image.Source as BitmapImage;
        if (bitmapImage != null)
            bitmapImage.UriSource = null;
        image.Source = null;

        if (String.IsNullOrEmpty(path))
        {
            //image.Source = new BitmapImage { UriSource = new Uri(Constants.RESOURCE_IMAGE_EMPTY_PRODUCT, UriKind.Relative) };
            return;
        }

        // If local image, just load it (non-local images paths starts with "http")
        if (path.StartsWith("/"))
        {
            image.Source = new BitmapImage { UriSource = new Uri(path, UriKind.Relative) };
            return;
        }



        {
            var request = WebRequest.Create(path) as HttpWebRequest;
            request.AllowReadStreamBuffering = true;
            request.BeginGetResponse(result =>
            {
                try
                {
                    Stream imageStream = request.EndGetResponse(result).GetResponseStream();
                    uiThread.Post(_ =>
                    {

                        if (path != this.SafePath)
                        {
                            return;
                        }
                        if (imageStream == null)
                        {
                            image.Source = new BitmapImage { UriSource = new Uri(path, UriKind.Relative) };
                            return;
                        }

                        bitmapImage = new BitmapImage();
                        bitmapImage.CreateOptions = BitmapCreateOptions.BackgroundCreation;
                        bitmapImage.SetSource(imageStream);
                        image.Source = bitmapImage;
                        //imageCache.Add(path, bitmapImage);
                    }, null);
                }
                catch (WebException)
                {
                    //uiThread.Post(_ =>
                    //{
                    //    image.Source = new BitmapImage { UriSource = new Uri(Constants.RESOURCE_IMAGE_EMPTY_PRODUCT, UriKind.Relative) };
                    //}, null);
                }
            }, null);
        }
    }


    private void OnUnloaded(object sender, RoutedEventArgs e)
    {
        var image = Content as Image;

        if (image == null)
            return;

        var bitmapImage = image.Source as BitmapImage;
        if (bitmapImage != null)
            bitmapImage.UriSource = null;
        image.Source = null;
    }
}

最后一点,Windows Phone ListBox 默认使用虚拟化和回收(使用的 ItemPanel 是 VirtualisedStackPanel).

Just as a final note, the windows phone ListBox is using virtualisation and recycling by default (the ItemPanel used is a VirtualisedStackPanel).

这篇关于具有自动内存清理功能的图像下载器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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