Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Saturday, December 28, 2019

How to Prevent memory leak and Profiling in Xamarin applications

Mobile Application planning, development, testing and  deployment go well as per the customer estimation but after a while the client was clamoring that the app is getting slower and slower when it was continuously being used up to the point where it will just crash suddenly but most of the developer unaware why it’s like this. In this article, you are going to learn how to use prevent memory leak and profiler in Xamairn 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:

You do incorrect memory management wherein 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 Knows what we can’t do but still we are doing as like below image, Same in Mobile Development also we all knows what can’t do, but still we are doing same mistake
I suggest to be extra careful when using 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 in 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 Mobile application you should define to developer with strike rule and TODO List and make sure your code review taken care following option for 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 StreamsGraphics, 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",
        // 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 all object cleanup, so the garbage collector no longer needs to call the objects' Object.Finalize override. Learn more MSDN portal .
public void Dispose()
   // Dispose of unmanaged resources.
   // Suppress finalization.

Test for memory leaks:

It’s a great practice to proactively test for memory leaks. And it’s not that hard. Here’s a short pattern you can use in the unit testing project.
void MemoryLeakTest()
  var weakRef = new WeakReference(leakyObject)
  // Ryn an operation with leakyObject

Getting Started Profiling:

Xamarin Profiler is a great tool created by Microsoft wherein it gives developers ways to profile or collect telemetry with your Mobile Applications using Visual Studio. It can also be paired with native profilers, like Xcode Instruments and Android Profiler, to ensure better app behavior and performance. The main function of the profiler is to collect and displays information about the Mobile App wherein the Developer can pinpoint, analyze and optimize areas in their application for a smooth experience by end users. There are different ways the Xamarin Profiler can help us like statistical.
The Xamarin Profiler has many features Allocation, Cycles, Data presented on each screen and Time profiler. It’s a graphical interface for the Mono log profiler, and supports profiling for following platform in Windows and mac machine.
  • Android, iOS, tvOS, and Mac applications on Mac
  • Android, iOS, and tvOS applications on Windows.
In this section, will learn common profiling scenarios and analyze and optimize iOS and Android applications.


We need Visual Studio Enterprise subscriber to unlock Profiler feature in either Visual Studio Enterprise on Windows or Visual Studio for Mac on a Mac. Download install following package in your mac or windows machine.
After successful installation, let get satrt use Profiling in Xamarin iOS and android application. Integrate Profiling is very simple steps, you need changes Project Property options in iOS and Android Project. 
Create new Xamairn Forms project using Visual Studio and Select iOS and Android platform is supported and follow below two steps for enabling the profiling in iOS and Android Project.


In Android Project, Right click on project > Select property > Select “Android Options” > Select options “Enable developer instrumentation”.


In iOS Project, Right click on Project > Select Property > Select “iOS Debug” Options and check the check box “Enable Profiling”.

Start the Xamarin Profiler:

Step 1: Build and run the application in iOS or Android. 
Step 2: In Visual Studio menu, Select Analyze or Tools main menu > Select Xamarin Profiler and open the Profiler and make sure before open profiler, the application needs to be built at least once in order to start a profiling session.
The Xamarin Profiler comes with following instruments: 
  • All Instruments
  • Allocations. 
  • Time Profiler. 
Once you have selected a Allocations options and you can also configure some options of how the memory profiling will proceed. You can either customize the frames, frequency or either select from the presets as shown below image.
Once you have clicked the Start Profiling button it will automatically launch your selected application on the selected device and you will be greeted with this window
In that above image denoted number with green marked and detail info below 
  • No 1 - Represents the actual graph of the Memory consumption with respect to time.
  • No 2 - Represents the different data categorized on your selected tab.
  • No 3 -Represents the information (Object name, count, size) displayed based on the selected tab.
  • No 4 - Represent the real time display of information based on the current snapshot.
  • No 5 - Represents the Selected device and the Application that is currently running.


Snapshots pane displays information about memory snapshots. To generate these while profiling a live application, click the Camera button in the toolbar at each point that you'd like to see what memory is retained and released. You can then click each snapshot to explore what is happening under the hood. Note that snapshots can only be taken when live profiling an app.

Time Profiler

The Time Profiler instrument measures exactly how much time is spent in each method of an application. The application is paused at regular intervals and a stack trace is run on each active thread. And Call Tree options will show amount of time spent in each method.
I hope you enjoyed for learning profiling and prevent memory leak issue. Let me state that Profilers are not only for memory leaks but also can be used in code optimization. Finally moving forward maybe you can also adapt or put in your development routine the profiling of your mobile applications.


I hope this article gave you some value to you, let we take a new year’s resolution is better memory management while doing C# programing. Please leave your feedback/query using the comments box, and if you like this article, please share it with your friends


  1. Nice article i was really impressed by seeing this blog, it was very interesting and it is very useful for me.also the information which you have mentioned here is correct and impressive. Really appreciate.
    Hire Xamarin Developer
    Xamarin Development Company

    1. Great Article android based projects

      Java Training in Chennai

      Project Center in Chennai

      Java Training in Chennai

      projects for cse

      The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training

  2. Great blog, but developing an application in react native gives you fast and attractive app as compare to other frameworks, this makes react native best cross platform app development framework.

  3. I really appreciate your knowledge and writing style! Thanks for sharing useful information. 🙂 is completely offshore IT company in Indore India

  4. Thanks to share this eye opening information as you know that In this modern era, mobile app development has become an asset for every businesses to take their organization to the next level.
    In this way xamarin app development is a potential way to create actionable mobile application.

  5. One of the best article and review i ever seen its very nice and informative . One of the best mac cleaner to clean a mac in one go.

  6. Very nice info would love to read such kind of blogs was very helpful indeed
    Mobile application development in Bangalore

  7. thanks for sharinf wonderful information. guys you can find some more information related to React Native vs Xamarin

  8. Publish Research Paper: Authors should submit the manuscript/paper that has been attentively proof-read and brilliance. Authors are mandatory to refer to the UIJRT manuscript/paper template format. This will assure fast processing and publication. Through E-mail acceptance or rejection, the notification will be sent to all authors. Fast Paper Publication

  9. As more and more mobile app development is taking place it becomes important for the development of the app to take place with keeping security in mind. This article guides well about the developments in xamarin and allows for the Mobile App Development in Android App Development and iOS App Development

  10. We are a leading Terrace offering waterproofing services providers in Bangalore. We understand that the terrace is dependent upon the most severe atmospheric conditions, for example, burning daylight, warmth, wind, and heavy rainfall during the rainstorm season. Even though the building plans join vital walks to assure the water stream to authorized sources, here and there it's barely enough. It is needed to shield the underlying substance from water penetration that can make extreme primary harm the solid or even wind up eroding the implanted steel.

  11. Sotophone brings on the magic of Symphony Atom II in their web portal. Just go to the website and watch.

  12. Get the leading Mobile apps and the integration with blockchain application development IoT App Development and Leading crypto fund management solutions for the businesses across various domains.

  13. I read your blog. The information you give in the blog is very good.
    mobile app development company
    android apps development
    iphone apps development
    Mobile Application Development Companies in Chennai
    mobile app development companies
    app development companies
    mobile app development company in India
    top app development companies
    top mobile app development company
    Android App Development Company in Chennai
    App Development Companies in Chennai
    App Development Company in Chennai
    Apps Development Companies in Chennai
    Apps Development Company in Chennai
    Best App Development Companies in Chennai
    Best Mobile App Development Companies in Chennai
    ios app development companies in Chennai
    List of app development companies in Chennai
    mobile App Development Company in Chennai
    Mobile Application Development Companies in Chennai
    Mobile Application Development Company in Chennai
    Mobile Apps Development Companies in Chennai
    top mobile app development companies chennai
    mobile app development
    top mobile app development company
    mobile application development
    mobile apps development
    offshore mobile app development
    offshore mobile application development
    top mobile app development companies in india
    top mobile apps development
    app development
    mobile application development companies
    best mobile app development company
    mobile app development companies in chennai
    Mobile App Development
    Mobile App Development Company
    custom mobile app development
    Native Mobile App Development Company in Chennai
    Android App Development Company
    IOS App Development Company in Chennai

  14. Hashstudioz Technologies let you develop the latest mobile application based on your business services covering the aspects of AI , IoT , Blockchain , and other technological implementations for an optimized Mobile Application architecture development.

  15. Get the latest technological advancements that make your business get the required growth with the utilization of IoT-enabled technological advancement. Hashstudioz brings you some of the finest resources for IoT development.

  16. Nice blog! I really loved reading through this Blog... Thanks for sharing such a very interesting post with us and keep blogging.
    Visit our website-
    hire xamarin developer
    web development company
    android development company

  17. Thank you for your post. This is excellent information. It is amazing and wonderful to visit your site. For more info:- Xamarin App Development

  18. This post is so interractive and informative.Keep updating with more information....
    Future Of Android Developer
    Scope Of Android Developer

  19. I really appreciate your post and it's really excellent. Want to read some more posts from your blog

    Machine Learning Training in Bangalore

  20. It's actually an important blog entry. This blog momentarily clarifies about APP Development. This is one of the unmistakable programming dialects generally utilized. A debt of gratitude is in order for sharing this decent article. You can reffer more important things on this blog Mobile App Development Services

  21. Very useful Post. I found so many interesting stuff in your Blog especially its discussion. Really its Great Article. All our Mobile App development services come with exceptional technical support.

    APP development company
    best app development company in india

  22. I think this is an informative post and it is very useful and knowledgeable. Hire front end developer suited to your business needs. it adds great value to your business and online presence.

    hire front end developer