Tuesday, October 15, 2019

Find, Fix, and Avoid Memory Leaks in C# .NET: 8 Best Practices

https://michaelscodingspot.com/find-fix-and-avoid-memory-leaks-in-c-net-8-best-practices/

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:
  1. Place a breakpoint where the instance of the class is created.
  2. 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.
  3. Finish the scenario that was supposed to free your instance from references.
  4. 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.
Report this ad
Important: This practice doesn’t work well in .NET Core 2.X debugger (issue). Forcing garbage collection in the same scope as the object allocation doesn’t free that object. You can do it with a little more effort by forcing garbage collection in another method out of scope.

No comments:

Post a Comment