Thursday, June 4, 2015

Handling the Heap: Xamarin Forms Memory issues on Android

Memory management is, by Xamarin's own admission, an advanced topic in their framework. In order to make the right design pattern decisions with the exciting Xamarin Forms library, you have to first understand what is going on in translation between C# and the native platform you are deploying to. In this article we will tackle the Android build using the Portable Class Library in a XF (Xamarin Forms) solution.

Your Garbage, My Garbage

Java is the language responsible for the native performance on your Android device. It's namespace handles garbage collection differently than the language we are using to build this XF application, which is C#. More than just the .Net approach to garbage collection is Xamarin's custom garbage collector as well. That's three to keep track of. Note that the C# namespace does not contain knowledge of the actual size of your native object - only a small pointer to it, which is exponentially smaller in size (maybe only a 2k object). When it gets collected in .Net/Xamarin Forms will be different than when the native platform disposes of it's objects. It's important to understand this, so you can tackle handling when objects are disposed of in the correct project - PCL or Device-Specific.

Custom Renderer Usings

A great rule of thumb is to wrap Java objects in a using statement when implementing anything on the Android project. For example, a code snippet inside of a Task method class will go from this:

var bitmap = await BitmapFactory.DecodeByteArrayAsync(imageData, 0, imageData.Length, options);
return bitmap;

To this:

using (var bitmap = await BitmapFactory.DecodeByteArrayAsync(imageData, 0, imageData.Length, options))
                return bitmap;

Using statements call Dispose() once the code inside of it has completed, queuing the object for the platform's garbage collector to free it from memory. It won't happen immediately, but it will promote it for priority collection, and should happen faster.