The app I am writing is suffering quite dramatically from a memory leak. Pretty much the entire object model is staying in memory when a user closes down a loaded project. The way I know this is because closing a project in my app barely effects the memory usage in the task manager and then opening a new project almost makes it double each time. I downloaded jetBrain's dotTrace Memory 3.5 but there is little (none) instructions for use. I kinda figured out how to use it and it shows that the whole object model is still in memory when i take a snapshot after a project has been closed down. Trawling through my projectClose code I can see no reason for this. Does anyone know of anything in particular that normally causes memory leaks in C# or of any tools or techniques for tracking down the problem. Its all well and good having an app that shows my entire object model is still loaded into memory but it doesnt show me what object or variable is storing it. Thanks in advance.
Probably the most common cause of managed memory leaks is unsubscribed event handlers.
There are a number of useful tools for tracking errors like this. Personally I like ANTS Memory Profiler and WinDbg/SOS. You want to find out what is rooting the object graphs. With WinDbg/SOS there's a !gcroot
command, that will tell you the roots of any given object.
Check Tess' blog for guides on how to troubleshoot memory problems using WinDbg/SOS.
Firstly, investigate whether the leak could be due to registration of event handlers as this is one of the easiest ways to accidentally root your objects. For example, if you have a class 'Bob' that adds one of its methods 'OnSomeEvent' as a delegate to an event that is raised by a long-living component of your system (e.g. 'UserSettingsManager') then objects of class 'Bob' will not be collected as they are kept alive by virtue of being an event handler (i.e. event callbacks are not weak references).
As an alternative to the commercial tools, there is an extension to the Windows debugger called SoS (Son of Strike) that you can use to debug managed applications. However, it is not the faint-hearted as it is a low-level, command-line tool that requires a lot of up-front learning. It is very powerful, however, and does not struggle so much with larger processes (in terms of heap consumption) as the commercial tools do.
In terms of the commercial profilers, I've had good experiences with Redgate's ANTS Memory Profiler (but I have had colleagues who hate it) so it may be worth trialing that.