如何在Windows Phone 8中释放图像缓存/内存?

时间:2014-02-28 17:45:05

标签: c# windows-phone-8 out-of-memory bytearray

在我的Windows Phone 8应用程序中,我有一个LongListSelector的页面,该页面绑定到1000个对象的列表,这些对象具有base64string的图像属性。现在为了显示图像,我编写了这个转换器,将bas64string转换为stream

public object Convert(object value, Type targetType, object parameter,  System.Globalization.CultureInfo culture)
{
    if (!value.ToString().Contains("http://"))
    {
        string str = value.ToString();
        byte[] bytes = Converter.FromBase64String(str);

        using (MemoryStream stream = new MemoryStream(bytes))
        {
            stream.Seek(0, SeekOrigin.Begin);

            BitmapImage image = new BitmapImage();
            image.SetSource(stream); 
            bytes = null;
            var memoryusage = string.Format("Memory: {0} bytes", 
            DeviceExtendedProperties.GetValue("ApplicationCurrentMemoryUsage"));
            Debug.WriteLine(memoryusage);
            return image;
        }
    }
    else
    { 
        return null;
    }
}

这就是记忆:

    Memory: 92549120 bytes
    Memory: 92946432 bytes
    Memory: 92946432 bytes
    Memory: 92946432 bytes
    Memory: 92946432 bytes
    Memory: 93192192 bytes
    Memory: 93192192 bytes
    Memory: 96079872 bytes
    Memory: 100700160 bytes
    Memory: 100700160 bytes
    Memory: 109568000 bytes
    Memory: 111734784 bytes
    Memory: 142852096 bytes
    Memory: 143056896 bytes
    Memory: 143056896 bytes
    Memory: 143261696 bytes
    Memory: 140791808 bytes
    Memory: 141103104 bytes
    Memory: 141529088 bytes
    Memory: 142151680 bytes
    Memory: 146784256 bytes
    Memory: 146784256 bytes
    Memory: 155066368 bytes
    Memory: 156368896 bytes

当内存等于或大于此156368896字节的某些字节时,应用程序将与EngineExecutionException崩溃。一旦我得到“OutOfMemoryException:

image.SetSource(stream);

显然这是一个记忆问题。我需要清除图像缓存但是如何?我在这个答案https://stackoverflow.com/a/12267163/1949475中看到了这个链接,但是我无法使用它。

注意:并非所有图像都同时显示,并且在我返回并再次返回页面后,应用程序占用了大量内存,从而更改要在LongListSelector中显示的数据。

1 个答案:

答案 0 :(得分:4)

在转换器类中设置

非常重要
BitmapImage image = new BitmapImage(); 
image.DecodePixelType = DecodePixelType.Logical; 
image.CreateOptions = BitmapCreateOptions.BackgroundCreation; 
image.CreateOptions = BitmapCreateOptions.DelayCreation; 
image.DecodePixelWidth = 56; 
image.DecodePixelHeight = 100;