Introduction
In a recent experience, mobile application planning, development, testing, and deployment were going well, as per the customer estimation, but after a while, the client was clamoring that the app was becoming slower and slower when it was continually being used. It reached the point where it would just crash suddenly but most of the developers were unaware why it’s like this. In this article, you are going to learn how to use prevent memory leak and profiler in a Xamarin Application.

Garbage Collection
We all know that in the .NET world, we have a very good friend called Garbage Collector. Basically, it is responsible on freeing up the used memory. As simple as it sounds, whether you are in a Desktop, Web or especially mobile where there are two worlds one is Managed and the other one is the native part which at times Garbage Collection is not enough to reclaim those used memories the cause of the slowdown Mobile app is due to Memory Leaks.

Beware of common memory leak sources
With incorrect memory management, an object is stored in memory but cannot be accessed by the running code, it’s always causing a memory leak in mobile application. We all know what we cannot do, but we are still doing things as in the below images. It's the same in Mobile Development also; we all know what can’t do, but still, we are making the same mistakes.

I suggest to be extra careful when using the below C# feature, and proactively check for memory leaks with techniques like the last best practice.
- Events, delegates or Messaging Centers in .NET are notorious for causing memory leaks. You can innocently subscribe to an event, causing a damaging memory leak without even suspecting.
- Custom control and Unknown Nuget package are event registered, such as Loaded, will not be unloaded until all events are unregistered. Always remember to unregister your events when you don't need them anymore and we are not sure all the objects or disposed.
- Images is a classical .net GC-Java GC problem when GC isn't aware of image size and won't release reference unless it is Disposed.
- Static variables, collections, and static events in-particular should always look suspicious. Remember that all static variables are GC Roots, so they are never collected by the GC.
- Caching functionality in mobile apps is necessary, any type of caching mechanism can easily cause memory leaks. By storing cache information in-memory, eventually, it will fill up and cause an OutOfMemory exception.
- Bindings can be dangerous. The rule of thumb is to always bind to a DependencyObject or to a INotifyPropertyChanged object. When you fail to do so, Xamarin will create a strong reference to your binding source (meaning the ViewModel) from a static variable, causing a memory leak
- Threads that never terminate – The Live Stack of each of your threads is considered a GC Root. This means that until a thread terminates, any references from its variables on the Stack will not be collected by the GC. This includes Timers as well. If your Timer’s Tick Handler is a method, then the method’s object is considered referenced and will not be collected.
Preventing Memory Leaks
Enterprise Mobile application knows memory leaks are like overloaded people on a bus or train. You might not notice when there are few of them, but you always make sure people enter in the bus with very limited and identify bus capacity based on that you need to allow the people into the bus. In a mobile application, you should define to the developer with a strike rule and a 'TO DO' list and make sure your code review has taken care of the following options to prevent memory leaks.

Using Statement
Xamairn Mobile application constantly uses unmanaged resources. The .NET framework itself relies heavily on unmanaged code for internal operations, optimization. Anytime you use Streams, Graphics, or Files, for example, you are probably executing unmanaged code. The using statement transforms the code into a try / finally statement behind the scenes, where the Dispose method is called in the finally clause.
- public void CreateFile()
- {
- using (var stream = new FileStream(@"\Document\SomeFile.txt",
- FileMode.OpenOrCreate))
- {
- // do stuff
- }// stream.Dispose() will be called even if an exception occurs
Dispose pattern
You implement a Dispose method to release unmanaged resources used by your application. The .NET garbage collector does not allocate or release unmanaged memory. The Dispose method performs an object clean up, so the garbage collector no longer needs to call the objects' Object. Finalize override. Learn more at the MSDN portal.
- public void Dispose()
- {
- // Dispose of unmanaged resources.
- Dispose(true);
- // Suppress finalization.
- GC.SuppressFinalize(this);
- }










muralikrishnan vPosted Jun 22, 2021, 4:53 PM
The above unit test case always fails as the Android will do the GC collect on its own.
Tahir AlviPosted Feb 5, 2020, 5:55 AM
Honestly in article writer explain the C# code memory leaks not the Xamrin specific. Both suing statement and dispose class is used for unmanaged code.
devi rajuPosted Jan 10, 2020, 10:02 AM
Interesting one. Thank you... :-)
Vidyadharran GPosted Jan 10, 2020, 10:01 AM
Recently i got drifted to mobile application development from web development..this will be useful for me from starting itself ...thanks bro for sharing such a nice article :)
NimishaPosted Jan 10, 2020, 7:46 AM
It's very interesting, This should be very useful to all xamairn developers, while developing we are missing this. Thanks Sir for sharing :)