Search code examples
c#.netmemory-leaksmemory-leak-detector

How do i find what is leaking in C#?


I have some C# code. I use code analyses to find all the places where i am not using using(){} or not calling dispose. That is done. Yet it still leaks. The code doesn't call DllImport except two functions (SetWindowPos, SetForegroundWindow) but those are never called (main instance doesnt use it. Other instance do but they live for a few seconds).

Somehow this code is leaking. How do i find out what the problem is?


Solution

  • Memory leaks in Managed code are usually due to objects being held in memory by an unintended reference. Events handers are common culprits here.

    You're going to want to get hold of a memory profiling tool. SciTech's .NET Memory Profiler is probably the best, though JetBrains' dotTrace and RedGate's ANTS are also both good.

    Microsoft has a free profiling tool, CLR Profiler, that can be used, though it's a bit more complicated. See here and here for some guidance.

    The DRONE profiler for .NET seems to have a free personal license, though I am not familiar with the tool myself. They have an article on finding memory leaks with their profiler here.

    The higher end versions of Visual Studio also contain profiling tools. MSDN contains the documentation on how to use them.