You would want to remove the handlers if the containing object is being kept in limbo after all references to it in your application have been removed.
For example...
public class LostInLimbo
{
private Villain _problem;
public void SetVillain(Villain problem)
{
problem.SomeEvent += this.SomeHandler;
_problem = problem;
}
}
Given this class, if we do the following:
Villain foo = new Villain();
LostInLimbo victim = new LostInLimbo();
victim.SetVillain(foo);
victim = null;
the instance victim
is now "leaked". It is referenced by foo
and therefore will not be collected; however, you cannot access this instance. Do this a few hundred thousand times and you might have an issue.
In this case, you would want LostInLimbo to implement IDisposable, where you could unhook the event:
var temp = _problem;
_problem = null;
if (temp != null_
temp -= this.SomeHandler;
Similarly, you might end up with a leak if you do this:
public class LostInLimbo
{
public Villain Problem {get;private set;}
public LostInLimbo()
{
Problem = new Villain();
Problem.SomeEvent += this.SomeHandler;
}
}
and do the following
var temp = new LostInLimbo().Villain;
Same situation. Villain holds a reference to the instance of LostInLimbo, but you do not have access to this instance. Again, implementing IDisposable will allow the instance of LostInLimbo to unhook itself. Of course, there are other issues with this, but its just an example.
If, however, you have this situation:
public class LostInLimbo
{
private Villain _problem;
public LostInLimbo()
{
_problem = new Villain();
_problem.SomeEvent += this.SomeHandler;
}
}
there are no worries. Only LostInLimbo holds a reference to _problem, and _problem holds no references to any instance of LostInLimbo except for the one that "owns" it. Once that instance is collected, so is _problem.
In response to your update, I would do the following.
First, when an item is added to the collection, the collection hooks to the item (override any method that adds an item to the collection). When an item is removed from the collection, the collection unhooks from the item (again, override any method that removes an item from the collection). I would also implement IDisposable to empty the collection on dispose. I would make sure that any type that used the collection also implements IDisposable.