Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OutOfMemory Exception in <BitmapImage>.SetSource()

I have created a pivot that dynamically download and hold several large images. I first download the image using webclient and write it into disk. than create an array of image list that holds all the images. The basic idea is that I only load images when it is needed. Say there is 12 images in my list. Pivot is showing only 1 image per slide. Assume we are viewing image 7. I proceed to preload image 6 & 8 for next slides.

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

When user navigate through slides, I keep the image preloaded between and unload outside "[ ]".

The code I used to preload image:

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 unload images:

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

The problem is, after several image is viewed(about 9 image). It throws an OutOfMemory exception in the line: bi.SetSource.

I checked that the unload function had worked properly( it does released the memory after calling Collect, and memory kept at a steady point)

But it still throws an OutOfMemory exception. What should I do?

Edit:
I just discovered that the memory in fact keeps going up
when navigating through slides. By calling:

Microsoft.Phone.Info.DeviceStatus.ApplicationCurrentMemoryUsage;

It gives the memories like:

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);

It is showing around 1.2~1.3 MB only.
What happened? Shouldn't the memory being released?

like image 780
user1510539 Avatar asked Jan 18 '26 17:01

user1510539


1 Answers

I end up with setting an Empty 1x1 transparent GIF to the image source the release the 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 released properly.

like image 196
user1510539 Avatar answered Jan 20 '26 09:01

user1510539



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!