Thursday, October 11, 2012

Viewing the .NET Finalizer Queue

In .NET, memory is managed via a garbage collector.  The collector works by processing the "Finalizer Queue".  Sometimes the queue can back up (the overall system is so busy that it can't release the items fast enough) and so you may need to come up with a new resource deallocation strategy.

In order to find the problematic objects, its useful to look at the queue at certain points when the system is under load to see what can be reclaimed sooner by implementing the IDisposable interface and freeing those objects in your code (thereby avoiding having them processed by the queue).

There is a third party tool to do let you view this information but it would make sense that there is an alternative way using Microsoft Visual Studio and it is described in this article by Tess Fernandez: .Net finalizer memory leak debugging with sos dll in visual studio.

There were a couple of noteworthy gotchas:

  1. When you connect the debugger to the running executable, you need to ensure that Native debugging is turned on
  2. The sos.dll extension that you load is done via the "immediate" window which is different from the "command" window.  To get an immediate window to open you can type immed into the command window.  From the immediate window you use the .load command highlighted in the article.
The best part about this tool is there doesn't appear to be anything you need to install.  The sos.dll is always there with .Net 2.0 or later.