我需要动态加载许多(有时数百个)缩略图.出于性能原因,我需要在有限数量的请求中执行此操作,我使用单个请求/响应进行测试.我正在为响应中的图像发送二进制数据,并使用MemoryStream将它们加载到BitmapImage中.这工作正常,直到我加载超过约80个缩略图,然后我得到灾难性失败例外.为了确保我的数据没有损坏,我尝试使用相同的字节数组多次加载BitmapImage,并在80次左右加载后崩溃.
下面是从字节数组加载图像的示例,已知字节数组具有有效的图像数据(png):
private BitmapImage LoadImage(byte[] imageData)
{
BitmapImage img = new BitmapImage();
MemoryStream stream = new MemoryStream(imageData);
img.SetSource(stream); // Exception thrown here after too many images loaded.
return img;
}
Run Code Online (Sandbox Code Playgroud)
然后我使用BitmapImage作为页面上Image元素的源,但错误发生在img.SetSource(...)上面的行中.
添加GC.Collect()到我正在加载缩略图图像的循环允许我加载更多图像,所以我认为这与内存管理有关,但我不知道我能做些什么来解决问题.