ImageSource not disposed and creating OutOfMemoryException

928 views Asked by At

I am working on a Xamarin.Forms application,

Inside one of my Page, I have multiple custom StackLayout (ActivityTypeView) containing an Image. These StackLayout are created and added dynamicaly inside a Grid in my Page.

Inside my ActivityTypeView I set the Image source as follow:

WorkIcon.Source = ImageSource.FromFile("disable.png");

(My image is saved inside my drawable folder)

The problem is that when I go to another Page and come back multiple time, I always end up at some point with an OutOfMemory Exception when trying to load the image.

I think somehow my ImageSource is not destroyed/Disposed when I change Page. So it will always, after I reload the same page multiple time, end up with this error.

I would like to know how to handle this situation. How can I dispose the ressource properly and when?

2

There are 2 answers

2
Timo Salomäki On BEST ANSWER

I've taken a habit of using the FFImageLoadingLibrary that takes care of properly caching and reusing the image resources. For example, in your case it would help you to always use the same in-memory image instead of loading a new one each time, eventually leading to an OutOfMemoryException.

You can simply replace all Image classes with the CachedImage and set quite a few properties that control caching, downsampling and other things. Here's the documentation: Xamarin.Forms API

1
momvart On

I'm no sure your image is large but if it is, you should not load the whole image file into the memory. Here's a way to load the image with bounds of imageview. It is for android but surely there's an equivalent for Xamarin.Forms