I need to dynamically load many (sometimes hundreds) of thumbnail images. For performance reasons I need to do this in a limited number of requests, I am using a single request/response for testing. I am sending the binary data for the images in the response and loading them into BitmapImage's using a MemoryStream. This works correctly until I load more than about 80 thumbnails, then I get the Catastrophic Failure exception. To make sure my data was not corrupt I tried loading a BitmapImage multiple times with the same byte array and it crashes after 80 or so loads.
Here is a sample of how the image is loaded from the byte array, the byte array is known to have valid image data (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;
}
I then use the BitmapImage as a source for an Image element on the page, but the error occurs in the img.SetSource(...)
line above.
Adding GC.Collect()
to the loop where I am loading thumbnail images lets me load a few more images, so I'm thinking this has something to do with memory management but I don't know what I can do to fix the problem.