Memory leaks in .Net applications are always proven to be a nightmare for developers. We often get an “OutOfMemoryException” that is nothing but due to memory leak only. There are many causes of memory leaks. For example, sometimes we forget to release an unmanaged resource, dispose of heavy objects (in other words, drawing objects), even holding a reference of managed objects longer than necessary can also lead to memory leaks.
So, if the application is small, one can analyze the code and figure out which object is causing a memory leak. But when it comes to a large application, it is not at all possible to figure it out manually. In that case, we need some tool, that can help us to figure out the area or object causing the memory leak. So, today I surfed the internet and came up with a tool called .Net Memory Profiler that can do an analysis for us and provide us the statistics of all the instances.
Ok, instead of getting more into the theory, let's jump quickly to the demo. I have a Windows Forms application named “MemoryLeakAnalysis”. Now I open the memory profiler that shows the following screen. The profiler can be run in two different modes, interactive (normal mode with a UI as shown below) and non-interactive mode. (Can only be used for automated testing as part of a script. It will not show any window.)
Click on "Profile application" and select the exe of your application, as shown below. If required, a command-line argument can also be provided
After clicking "Next >" you can decide the profiling level as Very low, Low, Medium, High, and so on. Moving further, you can also decide whether you want to enable the unmanaged resource tracker (collects information about handles, GDI handles, and so on), and finally click on "Start". Clicking on "Start" will launch your application (here my application name is "Test Leakage").
On the right-hand side, you can see various options, such as Collect snapshot, Stop profiling, Show real-time data. And just below that, we have "Investigate memory leaks". On clicking on "Investigate memory leaks", you will get the list of major steps that need to be taken up, in order to analyze the leakage.
So, looking at the instance graph and red arrows shown above will help us to identify where exactly a leak is happening.