user236215
user236215

Reputation: 7556

C# event subscribe and unsubscribe duplicates

Is there a problem if I subscribe to the same event three times with the eventHandler? e.g.

a.SomethingChanged += new EventHandler(ChangeHandler);
a.SomethingChanged += new EventHandler(ChangeHandler);
a.SomethingChanged += new EventHandler(ChangeHandler);

Does this cause ChangeHandler to be invoked 3 times instead of 1? What is best way to handle this?

Note that these redundancies are not together but different areas of code paths.

Similary, is there an issue with unsubscribing from an event that is not registered? e.g.

a.SomethingChanged -= new EventHandler(ChangeHandler);  //ChangeHandler was never registered

Upvotes: 9

Views: 4081

Answers (2)

ChrisF
ChrisF

Reputation: 137188

If you subscribe to an an event more than once then your handler will be called the corresponding number of times - in your example three.

Whether this is a problem or not depends on what your event handler does, but I'm assuming that you don't want it to be called multiple times.

There is no problem in unsubscribing from an event that you haven't subscribed to.

So if you're not sure what state your application is in (though you really should be) you can have:

a.SomethingChanged -= ChangeHandler;
...
a.SomethingChanged += ChangeHandler;

(Note: the new EventHandler(...) is syntactic sugar and can be omitted)

Upvotes: 14

Servy
Servy

Reputation: 203812

Is there a problem if I subscribe to the same event three times with the eventHandler?

Nope, it will just add the event handler three times.

Does this cause ChangeHandler to be invoked 3 times instead of 1?

Yes.

What is best way to handle this?

That depends on what you want; which you haven't specified. If you want a way to add an event handler if and only if it hasn't already been added, then just remove the event handler and then add it again:

a.SomethingChanged -= new EventHandler(ChangeHandler);
a.SomethingChanged += new EventHandler(ChangeHandler);

Is there an issue with unsubscribing from an event that is not registered?

No, it will just do nothing.

Upvotes: 5

Related Questions