I am using a FEZ Hydra and a CP7 display module. I am getting OutOfMemory Exception when I change the image on the screen some 40 times. The code for the image change is as follows
Image displayImage = new Image(new Bitmap(Resources.GetBytes(BinaryResource), Bitmap.BitmapImageType.Jpeg));
I have tried doing Debug.GC(true) but it does not help. Every time I change the image it uses approximately 125 KB of memory.
My image file size is 3 KB
Please let me know if there is a way to avoid the memory issues.
May be bitmap or Image does not release all of it’s resources when collected by GC.
Check if Bitmap and/or Image has a Dispose method.
If yes, you should definitely call it before giving up the last reference to it.
To do so you should store a image and bitmap reference as member variables. If they are != null before changing the image, call Dispose() to them, if they have.
You even might be able to reuse the Bitmap object, if the size is the same.
I’m not sure, but check if Bitmap has a method to copy it’s data from an array.
The 2nd possibility is RAM fragmentation.
If you allocate and free huge chunks of memory often, the RAM gets fragmented.
To allocate a large buffer as needed here, it must be available as a continuous block in RAM. Even if the smaller chunks are larger than the required memory, you get an OutOfMemoryException.
And finally 3rd possibility:
I think Bitmap uses LargeBuffer internally, because a normal byte array can have a maximum of 64k. The memory used for LargeBuffer is not managed by GC and needs to be freed separately. This would lead us to my 1st point.
You can read more about LageBuffer und Bitmaps here:
I just might have found another reason for this:
You have code to remove the old displayImage from the Canvas.
When you create the new Image, you assign it to displayImage.
Then you remove displayImage from canvas.Children, if it is contained.
But since you just created a new Image, it can not (never ever) be contained.
By this I guess you just put a new image above the old one, and that’s why the resources are never freed.
You have to store an reference to the image in a member variable, and use that in Contains and Remove.
I created Image instances of the images I need in ProgramStarted and used the same global variables to switch images. It worked. I am not getting the out of memory problem anymore. Thanks for your suggestion.
@ srivatsan - youre welcome