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

标签 c# windows-phone-8 out-of-memory arrays

在我的 Windows Phone 8 应用程序中,我有一个包含 LongListSelector 的页面,该页面绑定(bind)到一个包含 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

At memory equals to or maybe some bytes greater than this 156368896 bytes, the application crashes with the EngineExecutionException. Once I got "OutOfMemoryException for this:

image.SetSource(stream);

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

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

最佳答案

在你的转换器类中设置很重要

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

关于c# - 如何在 Windows Phone 8 中释放图像缓存/内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22102212/

相关文章:

c# - 尝试添加叠加层以映射错误

c# - 在 EF 5.0 中链接 OR 条件

c# - HttpWebRequest.GetRequestStream() 在 Windows 7/Vista 下因 SSL 连接超时而中断

javascript - Node.js 堆内存不足

grails - Grails Run-App内存不足错误

c# - 使用 Process 在后台模式下打开文件

c# - 将路径转换为几何形状

windows-phone-8 - Windows Phone 8 设备错误开发测试

javascript - 无法在 IE10 中创建 IndexedDB 数据库

android - 扩充布局时出现 OutOfMemoryError