views:

317

answers:

3

How to detect memory leaks in C# application? What tools need to use? What best practices do you know?

+5  A: 

Detecting memory leaks is not an easy task and there's no definitive answer to this question. You could use profiler tools such as the ANTS Memory Profiler or dotTrace. You could also take a look at the CLR Profiler from Microsoft which is free but is more difficult to use.

Darin Dimitrov
+1 for ANTS; the Red Gate tools are very nice.
David Lively
A: 

Memory leaks are difficult to code in C# because of the garbage collector. The GC will automatically free objects at some point after no more references. The only way you can "leak" memory is to leave an unintended strong reference around.

I second the call for dotTrace. I have used it and it works well. I've also used ANTS, but didn't like it as well.

Dark Falcon
+1  A: 

If you are concerned that you may have a memory leak in C#, the first thing to do is identify what kind of leak you may have. C# is garbage collected, so memory leaks aren't common. The most common sources are holding onto references to large objects (like images), large object trees (like collections), or not cleaning up unmanaged objects (native Windows objects allocated through P/Invoke, file handles or DB connections). Disposing of IDisposable objects can also free up memory faster, resulting in a smaller memory footprint.

Snarfblam