I am working on a .NET application where there appears to be a memory leak. I know the text-book answers, that events should be unsubscribed, disposable objects should be disposed etc…
I have a test harness that can reproduce the error. In the finalizer of a certain class I write to console
public class Foo
{
// Ctor
public Foo()
{
}
~public Foo()
{
Console.WriteLine("Foo Finalized");
}
}
In the test harness, I am creating a single instance of Foo (which in turn creates and interacts with hundreds of other types) then removing it and invoking the Garbage collector.
I am finding the Foo Finalizer is never called. I have a similar class with this setup which is finalized as a control test.
So my question is this:
How can I determine using commercial or open source tools exactly what
is holding a reference to Foo?
I have a professional license to dotTrace Memory profiler but can’t figure out from the help files how to use it.
Update: I am now using dotMemory 4.0, which is the successor to the (good, but unusable) dotTrace Memory 3.5.
The finalizer isn’t deterministically called, so beware of using it to track things in a reliable way. If you remove the finalizer and instead use a
WeakReference<Foo>you should be able to determine whether the object was collected.All memory profilers should be able to find an issue such as this, but with varying degree of difficulty. I have personally used ANTS which is very easy yo use, but not free. It will help you show a reference diagram to the Foo instance, all the way from a GC root object. Seeing this diagram it is usually easy to spot who is holding the reference.