Mark Cooper
Mark Cooper

Reputation: 6884

.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?

Upvotes: 5

Views: 473

Answers (5)

Maxim Alexeyev
Maxim Alexeyev

Reputation: 1031

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

Upvotes: 0

pedrofernandes
pedrofernandes

Reputation: 16854

I have a code for it. Its 2 classes for help access to events

Event Classes

And in my code introduce this:

alt text http://img440.imageshack.us/img440/1656/featurer.jpg

Now you can debug events entering in

CSoft.Core.EventHelper.Raise();

Upvotes: 1

Per Erik Stendahl
Per Erik Stendahl

Reputation: 883

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

Upvotes: 1

John Nicholas
John Nicholas

Reputation: 4836

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.

Upvotes: 1

Roger Lipscombe
Roger Lipscombe

Reputation: 91825

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.

Upvotes: 18

Related Questions