如何在Windows Phone 8中释放图像缓存/内存?
在我的Windows Phone 8应用程序中,我有一个带有LongListSelector
的页面,该页面绑定到1000个对象的列表,这些对象具有用于image的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; } }
这就是记忆:
内存:92549120字节 内存:92946432字节 内存:92946432字节 内存:92946432字节 内存:92946432字节 内存:93192192字节 内存:93192192字节 内存:96079872字节 内存:100700160字节 内存:100700160字节 内存:109568000字节 内存:111734784字节 内存:142852096字节 内存:143056896字节 内存:143056896字节 内存:143261696字节 内存:140791808字节 内存:141103104字节 内存:141529088字节 内存:142151680字节 内存:146784256字节 内存:146784256字节 内存:155066368字节 内存:156368896字节
在内存等于或大于此156368896字节的某些字节时,应用程序崩溃并发生EngineExecutionException
。 一旦我得到“OutOfMemoryException:
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;