4. Use “Make Object ID” to find memory leaks
In my last article 5 Techniques to avoid Memory Leaks by Events in C# .NET you should know I showed a technique to find a memory leak by placing a breakpoint in the class Finalizer. I’ll show you a similar method here that’s even easier to use and doesn’t require code changes. This one utilizes the Debugger’s Make Object ID feature and the Immediate Window.
Suppose you suspect a certain class has a memory leak. In other words, you suspect that after running a certain scenario, this class stays referenced and never collected by the GC. To find out if the GC actually collected it, follow these steps:
- Place a breakpoint where the instance of the class is created.
- Hover over the variable to open the debugger’s data-tip, then right-click and use Make Object ID. You can type in the Immediate Window $1 to see that the Object ID was created correctly.
- Finish the scenario that was supposed to free your instance from references.
- Force GC collection with the known magic lines
5. Type $1 again in the immediate window. If it returns null, then the GC collected your object. If not, you have a memory leak.
Here’s me debugging a scenario that has a memory leak:
And here’s me debugging a similar scenario that doesn’t have a memory leak:
You can force garbage collection in the end by typing the magic lines in the immediate window, making this technique a fully debugging experience, with no need to change code.
No comments:
Post a Comment