我知道过去曾在这里问过非常相似的问题 - 但都没有解决我的问题:
我将内存中的图像加载到 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!)
你甚至没有使用 Profilers 找到这个 - 只有 .net Memory Profiler 让我走上了正轨(因为它在所有字节都在的非托管内存中 - 所以 ANTS 告诉我“.NET 正在使用 367,3MB 中的 19,24MB 私有分配给应用程序的字节数” - 不错):
无论我尝试什么 - 我都不会消除这种泄漏。尝试过(一次和一次):
- 清除视觉树/卸载时删除图像
- 将图像源设置为 null
- 在 Rectangle 中使用 ImageBrush 而不是 Image
- 其他不释放 MemoryStream 的 CacheOptions
- 不要冻结图像
我不明白 - 真的!一旦我停止使用源中的图像,一切都很好(没有泄漏)。
有人我可以尝试任何选择吗?
备注 似乎这根本不是错误(请参阅我的第二条评论) - 我必须检查这个,所以我现在让问题打开 - 也许这也可以帮助解决其他问题