我知道过去这里曾经问过非常类似的问题,但是对于我的问题没有解决方法:
我将一张图片从内存中加载到一个BitmapImage对象中:
private static BitmapImage LoadImage(byte[] imageData)
{
if (imageData == null || imageData.Length == 0) return null;
var image = new BitmapImage();
using (var mem = new MemoryStream(imageData))
{
mem.Position = 0;
image.BeginInit();
image.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
image.CacheOption = BitmapCacheOption.OnLoad;
image.UriSource = null;
image.StreamSource = mem;
image.EndInit();
}
image.Freeze();
return image;
}
然后使用此方法(使用INotifyPropertyChange)将生成的BitmapImage绑定到页面上Image对象的Source属性中。
问题是:这会导致内存泄漏(在我的情况下,2-3张图片会占用高达300MB的内存!)
即使使用Profiler也找不到这个问题 - 只有.NET Memory Profiler可以帮助我解决问题(因为所有字节都位于非托管内存中,所以ANTS告诉我““.NET正在使用19.24MB的367.3MB总私有字节分配给应用程序” - 很好): 无论我尝试什么 - 我都无法消除这个内存泄漏。已经尝试过以下方法(单独和同时):
- 清除Visual-Tree / 在Unload时删除Image - 将Image-Source设置为null - 在Rectangle中使用ImageBrush而不是Image - 使用其他CacheOptions而不是Dispose MemoryStream - 不要Freeze Image 但是我真的不知道该怎么处理了!一旦我停止使用Source中的Image,一切都没问题(没有内存泄漏)。
有人有任何建议吗?
备注: 似乎这根本不是bug(请参见我的第二个评论)- 我必须检查这一点,所以我现在将问题保持开放状态 - 也许这也可以帮助解决其他相关问题。