Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Eventhandler Management

I have an event handler in code that I see is getting called multiple times when I am expecting it to only be called once.

In the past this has been because I have defined the delegation in the wrong place (so more that one delegate is added to the event handling list), but on this occastion this is only being set once (in the class constructor).

Rather than continuing to manually search through my code looking for errors, is there a (simple) pragmatic approach I can take to figuring out where event handlers are being assigned?

like image 644
Mark Cooper Avatar asked Jul 01 '09 14:07

Mark Cooper


1 Answers

You can replace the default:

public event EventHandler MyEvent;

...with

private EventHandler _myEvent;

public event EventHandler MyEvent
{
    add { _myEvent += value; }
    remove { _myEvent -= value; }
}

Then you could put logging or breakpoints inside the add/remove functions and look at the call stack.

like image 118
Roger Lipscombe Avatar answered Oct 16 '22 14:10

Roger Lipscombe