OutOfMemory exception in <BitmapImage> .SetSource ()

I created a pivot that dynamically loads and holds multiple large images. First, I download the image using webclient and write it to disk. than to create an array of image list containing all images. The basic idea is that I only load images when needed. Let's say I have 12 images on my list. Pivot only shows 1 image per slide. Let's assume we're previewing image 7. I'm going to preload images 6 and 8 for the next slides.

1, 2, 3, 4, 5, [6, {7}, 8], 9, 10, 11, 12

      

When the user navigates through the slides, I save the image, preloaded between and unloaded outside "[]".

The code I used for the preview:

BitmapImage bi = new BitmapImage();
bi.SetSource(GetStream(fileName);
IMGSource = bi; // IMGSource<ImageSource> referenced by the xaml in Image Binding IMGSource.

      

The code I used to offload images:

IMGSource = null;
GC.Collect(); // I force the program to Garbage collect since the image is really large.

      

The problem is that after viewing multiple images (about 9 images). He gives OutOfMemory exception in the line: bi.SetSource

.

I have verified that the offload function is working as expected (it frees memory after calling Collect and the memory is kept at a stable point)

But it still throws the exception OutOfMemory

. What should I do?

Edit:
I just discovered that memory actually keeps growing as I navigate through slides. By calling:

Microsoft.Phone.Info.DeviceStatus.ApplicationCurrentMemoryUsage;

      

This gives the following memories:

54.7 MB, 76.91 MB, 111.94 MB, 105 MB, 112.71 MB, 141.93 MB, 148.42 MB, Exception thrown

      

But by calling:

GC.GetTotalMemory(false);

      

Shown only 1.2~1.3 MB

.
What happened? Shouldn't the memory be freed?

+3


source to share


1 answer


I ended up setting a 1x1 blank transparent GIF for the image source, freeing up memory.

public static byte[] EMPTY_IMAGE = new byte[]{
    71, 73, 70, 56, 57, 97, 1, 0, 1
    , 0, 128, 0, 0, 255, 255, 255
    , 0, 0, 0, 33, 249, 4, 1, 0, 0
    , 0, 0, 44, 0, 0, 0, 0, 1, 0, 1
    , 0, 0, 2, 2, 68, 1, 0, 59
};

      

And then just use:



bi.SetSource(new System.IO.MemoryStream(MYCLASS.EMPTY_IMAGE));

      

And the memory seems to be released properly.

+1


source







All Articles