What strategies and tools are useful for finding memory leaks in .NET?


I wrote C++ for 10 years. I encountered memory problems, but they could be fixed with a reasonable amount of effort.

For the last couple of years I've been writing C#. I find I still get lots of memory problems. They're difficult to diagnose and fix due to the non-determinancy, and because the C# philosophy is that you shouldn't have to worry about such things when you very definitely do.

One particular problem I find is that I have to explicitly dispose and cleanup everything in code. If I don't, then the memory profilers don't really help because there is so much chaff floating about you can't find a leak within all the data they're trying to show you. I wonder if I've got the wrong idea, or if the tool I've got isn't the best.

What kind of strategies and tools are useful for tackling memory leaks in .NET?

3/31/2011 7:14:15 PM

Accepted Answer

I use Scitech's MemProfiler when I suspect a memory leak.

So far, I have found it to be very reliable and powerful. It has saved my bacon on at least one occasion.

The GC works very well in .NET IMO, but just like any other language or platform, if you write bad code, bad things happen.

10/9/2008 1:17:22 PM

Just for the forgetting-to-dispose problem, try the solution described in this blog post. Here's the essence:

    public void Dispose ()
        // Dispose logic here ...

        // It's a bad error if someone forgets to call Dispose,
        // so in Debug builds, we put a finalizer in to detect
        // the error. If Dispose is called, we suppress the
        // finalizer.

        // If this finalizer runs, someone somewhere failed to
        // call Dispose, which means we've failed to leave
        // a monitor!
        System.Diagnostics.Debug.Fail("Undisposed lock");

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow