16
I have an application which has some memory leaks due to events not being detached before an object reference is set to null. The applicaiton is quite big and its difficult to find the memory leaks by looking at the code. I want to use sos.dll to find the names of the methods that are the source of leaks but I'm getting stuck. I set up a test project to demonstrate the problem.
Here I have 2 classes, one with an event, and on the listens to that event as below
namespace MemoryLeak
{
class Program
{
static void Main(string[] args)
{
TestMemoryLeak testMemoryLeak = new TestMemoryLeak();
while (!Console.ReadKey().Key.Equals('q'))
{
}
}
}
class TestMemoryLeak
{
public event EventHandler AnEvent;
internal TestMemoryLeak()
{
AnEventListener leak = new AnEventListener();
this.AnEvent += (s, e) => leak.OnLeak();
AnEvent(this, EventArgs.Empty);
}
}
class AnEventListener
{
public void OnLeak()
{
Console.WriteLine("Leak Event");
}
}
}
I break into the code, and in the intermediate window type
.load sos.dll
then I use !dumpheap to get the objects on the heap of the type AnEventListener
!dumpheap -type MemoryLeak.AnEventListener
and I get the following
PDB symbol for mscorwks.dll not loaded
Address MT Size
01e19254 0040348c 12
total 1 objects
Statistics:
MT Count TotalSize Class Name
0040348c 1 12 MemoryLeak.AnEventListener
Total 1 objects
I use !gcroot to work out why the object is not being garbage collected
!gcroot 01e19254
and get the following
!gcroot 01e19254
Note: Roots found on stacks may be false positives. Run