具有自动内存清理功能的图像下载器

本文关键字:功能 图像 下载 内存 | 更新日期: 2023-09-27 18:33:38

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

一种可能的方法是在导航自时遍历所有图像并清理它们。

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

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

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}"/>

因此,乍一看,它工作正常,但是如果向下滚动并向上返回,图像会随机更改。

编辑:在这种情况下,目前,我只使用纯ListBox,没有虚拟化(但在其他情况下期望它(。

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

具有自动内存清理功能的图像下载器

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

...
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;
                }
                 ....

编辑:代码中存在几个问题: -开关寄存器附加到寄存器,寄存器附加是用于附加属性而不是普通依赖属性 -调用 OnLoaded in OnSourceWithCustomRefererChanged 因为 SafePath 属性更改实际上可以在加载元素后 apppen - 在onLoaded的开头添加清除uri和源,以便在路径为空时清除图像

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

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(。