我知道过去曾在这里提出过非常类似的问题 - 但都没有解决我的问题:
我将内存中的图像加载到 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!)
You don't even find this using Profilers - only the .net Memory Profiler got me on track (as it's in unmanaged memory where all the bytes go - so ANTS tell me ".NET is using 19,24MB of 367,3MB total private bytes allocated to the application" - nice):
无论我如何尝试,我都无法消除这种泄漏。
尝试过(单个且一次全部):
- 清除视觉树/删除卸载时的图像
- 将图像源设置为空
- 在 Rectangle 中使用 ImageBrush 而不是 Image
- 其他 CacheOptions 而不释放 MemoryStream
- 不要冻结图像
我不明白这一点——真的!
一旦我停止使用源中的图像,一切就正常了(没有泄漏)。
有人我可以尝试什么选择吗?
REMARK看来这根本不是错误(请参阅我的第二条评论)-我必须检查这一点,所以我现在要开放这个问题-也许这也可以帮助解决有关此问题的其他问题