Using the “+=” notation when creating delegate event is a really fast
way of coding but there is a caveat if the delegate is declared in the
wrong place. for example declaring the handler inline, in a method:
private void btn_Click(object sender, System.Windows.RoutedEventArgs e)
{
EventBus.Event+= new EventHandler(EventBus_Event);
//….do code here
}
When the btn_Click method is fired, an event handler is added to the
EventBus.Event event. The clue (and problem) here is the worded
“added”. If the btn_Click method is fired again, another identical
handler is added, so now you have two. These will continue processing
requests asyncronously, and continue to fire off your additional
logic.. oh dear!
To resolve this, simply abstrac the Event Delegation away from the UI
method calls, unless they are being specifically created and removed
for specific scenarios. I now add mine during class initialisation for
generic events:
private void EventBusDelegateEventHandlers()
{
//event handlers, these delegate control from the EventBus events.
EventBus.Event1+= new EventHandler(EventBus_Event1);
EventBus.Event2+= new EventHandler(EventBus_Event2);
EventBus.Event3+= new EventHandler(EventBus_Event3);
EventBus.Event4+= new EventHandler(EventBus_Event4);
}
I’m also using a centralised EventBus class that allows me to call and
handle events across classes.
Leave a Reply