C# Event Delegates

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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

A WordPress.com Website.

Up ↑

%d bloggers like this: