We all know managed code can have memory leaks. You can find a good example here: A .NET memory leak you did not think about. Microsoft provides us with the CLR Profiler, an open source tool for analyzing the behavior of your managed application, which you can download here. It contains very good documentation about the different functions of the tool, however I still find it a bit hard to start with, so here is a simple step-by-step example of how to use it. After you finish downloadoing it , extract the files and open the directory. there you will find the manual, you can read it later… Navigate to CLRProfiler\Binaries\x86 (or x64) and run CLRProfiler.exe.
Click “Start Application…” And select your application. I’ll provide a simple example soon… Now that your application is running, you see the other two buttons are enabled. perform some “memory leak operations” and click “Show Heap now”. I used this simple console application to simulate a “memory leaking” application. (If you dont understand why this application “leaks” memory, read here A .NET memory leak you did not think about):
class Program { class MyClass { public MyClass() { AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; bigMem = new byte[1000]; } void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { Console.WriteLine("UnhandledException"); } byte[] bigMem; } static void Main(string[] args) { for (int i = 0; i < 1000; i++) { MyClass mc = new MyClass(); } Console.ReadKey(); } }
After click the button you get “Heap Graph” window:
“The heap graph shows you all the objects in the garbage collection heap, along with their connections.” - you can see all the objects that are referenced by other objects, and see all the way from the root object to you object so you can understand exactly why your objects are still alive.
I Find the ClrProfiler easy to track leaks with. It doesn’t have the fancy UI some other tools have but its free and helpful…
We pay for user submitted tutorials and articles that we publish. Anyone can send in a contribution
Learn More
Sam Said on May 30, 2008 :
Good technique
Some devs will argue that this isn’t a realy memory leak, but I don’t think it is worth arguing over. Thanks for posting