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
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:
(Note: the
new EventHandler(...)is syntactic sugar and can be omitted)