Memory Leaks in C# WPF

15,984

Solution 1

Break into the debugger and then type this into the Immediate window:

.load C:\Windows\Microsoft.NET\Framework\v2.0.50727\sos.dll

The path to sos.dll varies. The way to find out the correct path is to look for mscorwks.dll in the Modules pane. Wherever that is loaded from is the correct path for sos.dll.

Then type this:

System.GC.Collect()

That will ensure anything not reachable is collected. Then type this:

!DumpHeap -type <some-type-name>

This will show you a table of all existing instances, with addresses. You can find out what is keeping an instance alive like this:

!gcroot <some-address>

Solution 2

.NET Memory Profiler is an excellent tool, and one that I use frequently to diagnose memory leaks in WPF applications.

As I'm sure you're aware, a good way to use it is to take a snapshot before using a particular feature, then take a second snapshot after using it, closing the window, etc. When comparing the two snapshots, you can see how many objects of a certain type are being allocated but not freed: this is a leak.

After double-clicking on a type, the profiler will show you the shortest root paths keeping objects of that type alive. There are many different ways that .NET objects can leak in WPF, so posting the root path that you are seeing should help identify the ultimate cause. In general, however, try to understand why those objects are holding onto your object, and see if there's some way you can detach your event handlers, bindings, etc. when the window is closed.

I recently posted a blog entry about a particular memory leak that can be caused by certain bindings; for that specific types of leak, the code there is useful for finding the Binding that's at fault.

Share:
15,984
Justin Bozonier
Author by

Justin Bozonier

I've been a software engineer for a few years. I love what I do and I'm always trying to learn more. Advice and critical discussions are welcome! Currently studying discrete math, multivariable calculus, algorithm design and analysis, and data structures (mainly graphs). I am also researching what I think my future field will be. I'm leaning towards soft computing/machine learning currently. Right now it's academia, but most things start out that way. I think it will be huge when enough people completely grok it.

Updated on July 29, 2022

Comments

  • Justin Bozonier
    Justin Bozonier almost 2 years

    I could use some advice on tracking down the cause of memory leaks in C#. I understand what is a memory leak and I get why they occur in C# but I'm wondering what tools/strategies have you used in the past to resolve them?

    I am using .NET Memory Profiler and I've found that one of my huge main objects is staying in memory after I close the window it manages but I'm not sure what to do to severe all links to it.

    If I'm not being clear enough just post an answer with a question and I'll edit my question in response. Thanks!