Skip to content
Koray Sarıtaş edited this page Jan 15, 2020 · 5 revisions

Here is a classic memory leak:

  • add a method / callback from an instance to a delegate / event
  • don't keep any reference on the instance
  • never unsubcribe / remove from the delegate / event

The "Lone Targets" analysis will help you to spot this kind of issues. Be careful, it can be slow because for each delegate type, it will check every subscribers of each instances. If one of the subscribers has only one refernce, it's considererd as "Lone trget" that can't be unsubscribed and never garbage collected.

Double click on an instance to display details about it:

In this example, the instance with address "20582C0" is refered only once : in a field named "_target" in an instance of type "ClassWithEventHandlers".

Let's have a look at the code that gave the dump in the screenshot:

var obj = new ClassWithEventHandlers();
var firstCallBack = new FirstCallBacks();
obj.FirstEventHandler += firstCallBack.MyFirstCallBack;
if (i >= M)
{
     objects.Add(firstCallBack);
}

The first M instances of firstCallBack are not added to the list "objects" so their are only referenced by the event FirstEventHandler from the type ClassWithEventHandlers.

I hope I'm clear, if not, do not hesitate to send an issue