I don't want to get off on a rant here, but....

Avatar

Technology, Programming, Complaints, etc.

Articles tagged with 'delgates'

Avoiding duplicate Event subsubscriptions

I've recently stumbled upon .Net Events, well re-stumbled since I obviously knew about them w.r.t. Web Forms, but they are a painful faded memory at this point, thanks to Monorail.  I really like .Net Events for writing code that can be super decoupled from infrastructure concerns like logging, as well as for objects that might need to relay status or other "events" to their parent without having to pass maintain a reference to the parent. 

The only real downside is if you subscribe multiple times to an event, += in C#, you get called multiple times when the Event fires.  I'm sure there's some upside to this in some convoluted usage scenario, but I sure can't think of it.  So I had written a bunch of helper methods to subscribe a given handler to a given event, but do it in a non-duplicate fashion.  As far as I can tell there's no way to ask the event who's subscribed in any meaningful way, at least w.r.t. dupe avoidance, so I just remove the handler before adding it:

handler -= value;
handler += value;

This was fine, but it required calling subEvent(handler); rather than using the default += method of associating a handler with an Event.  To get around this I found the this very handy post on stackoverflow.  This allowed me to handle the call to the duplicate prevention method from add, thereby keeping the normal sytax for Event handlers. 

The one gotcha here is you need the protected Event as well, because when you define the add, remove for your public Event you lose the ability to reference it like a normal Event. Some people have done more in-depth IL analysis of why, but for my purposes, I just use the protected Event when I want to throw it or otherwise use it so I don't get "The event "blah" can only appear on the left hand side of += or -=" errors