gpt4 book ai didi

.net - Silverlight:流中的 BitmapImage 引发异常(灾难性失败(HRESULT 异常:0x8000FFFF (E_UNEXPECTED)))

转载 作者:行者123 更新时间:2023-12-02 03:38:26 25 4
gpt4 key购买 nike

我需要动态加载许多(有时数百个)缩略图。出于性能原因,我需要在有限数量的请求中执行此操作,我使用单个请求/响应进行测试。我正在发送响应中图像的二进制数据,并使用 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;
}

然后,我使用 BitmapImage 作为页面上 Image 元素的源,但错误发生在上面的 img.SetSource(...) 行中。

GC.Collect() 添加到加载缩略图的循环中可以让我加载更多图像,所以我认为这与内存管理有关,但我不这样做不知道我能做些什么来解决这个问题。

最佳答案

我认为引用微软在上述错误报告中提供的答案是值得的,因为它非常简洁地描述了问题,并提供了推荐的解决方案:

When Silverlight loads an image, the framework keeps a reference and caches the decoded image until flow control is returned to the UI thread dispatcher. When you load images in a tight loop like that, even though your application doesn't retain a reference, the GC can't free the image until we release our reference when flow control is returned.

After processing 20 or so images, you could stop and queue the next set using Dispatcher.BeginInvoke just to break up the work that is processed in one batch. This will allow us to free images that aren't retained by your application.

I understand with the current decode behavior it's not obvious that Silverlight is retaining these references, but changing the decoder design could impact other areas, so for now I recommend processing images like this in batches.

Now, if you're actually trying to load 500 images and retain them, you are still likely to run out of memory depending on image size. If you're dealing with a multi-page document, you may want to instead load pages on demand in the background and release them when out of view with a few pages of buffer so that at no point do you exceed reasonable texture memory limits.

关于.net - Silverlight:流中的 BitmapImage 引发异常(灾难性失败(HRESULT 异常:0x8000FFFF (E_UNEXPECTED))),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6627164/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com