May 26, 2010

Beware of using anonymous delegates for event handlers

First found a description of this issue here
There is a problem unsubscribing to an event
Check out the following code:
EventHandler onXXX =
 delegate(object sender, XXXEventArgs e)
 {
  onXXXCallCount++;
  xxxs.Add(e.LastXXX);
 };
... 
m_YYY.OnXXX += onXXX;
...
// The anonymous event handler stays on the event handler until removed
// or the parent object is disposed of!
m_YYY.OnXXX -= onXXX;

No comments: