views:

132

answers:

5

Hi,

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?

Thanks Mark

+14  A: 

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.

Roger Lipscombe
Nice suggestion +1
DoctaJonez
That is a very simple and neat solution - works like a charm. Thank you.
Mark Cooper
+1  A: 

if you are using vb.net then are you sure that you are not adding the handler in a method and also using the handles keyword?

this causes an event to be handled twice.

John Nicholas
Good idea, but again this focuses on manual searching. Also I'm using C#. Thanks anyway.
Mark Cooper
+1  A: 

Install Resharper, then right-click on your event and select "Find usages".

Per Erik Stendahl
Would love to, but I don't have licence or budget for it :-(
Mark Cooper
I would say it pays for itself in about 1 month. I would never accept working without (or something similar) again.
Per Erik Stendahl
+1  A: 
pho3nix
Good suggestion, but Rogers idea of a customised accessor is really simple and works like a charm. Thanks for you input anyway. Mark
Mark Cooper
A: 

You can change name (not using Visual Studio re-factoring tools, just simply change name in the code) and see where compiler breaks.

Maxim Alexeyev