In class’s derived from a Component I sometimes see events declared like:
private static readonly object LoadEvent = new object();
public event EventHandler<MyEventArgs> Load
{
add { Events.AddHandler(LoadEvent, value); }
remove { Events.RemoveHandler(LoadEvent, value); }
}
protected virtual void OnLoad(MyEventArg e)
{
var evnt = (EventHandler<MyEventArg>)Events[LoadEvent];
if (evnt != null)
evnt(this, e);
}
Instead of just:
public event EventHandler<MyEventArgs> Load;
protected virtual void OnLoad(MyEvent e)
{
if (Load != null)
Load(this, e);
}
I’m tempted to to refactor to use the shorter method, but I am hesitant in case there are some advantages to using the Component EventHanderList that I am missing.
The only advantages I can currently think of are:
- When the component is disposed, all items in the EventHandlerList are removed, effectively automatically unhooking event handlers.
- Possibly less memory fragmentation because of all the attached delegates going into the single EventHandlerList.
Is there anything else?
(This is not a question about the general use of explicit add + removes on events.)
This is good for sparse events. UI controls tend to have dozens (sometimes upwards of 100) events. If a field-like-event was used for each, then each event requires a reference backing-field. With 100 events, that is 400 bytes on x86 or 800 bytes on x64, even if not a single event is subscribed.
As an example, a winforms
System.Windows.Forms.Formhas 91 events before you’ve added any. Every singleControlinstance has at least 69.So; a windows form with a few labels, input boxes and buttons could easily have an extra 2000 reference fields (16k on x86) most of which are doing nothing.
The
EventHandlerListis essentially a key/value lookup, which means that if only 3 events are subscribed (I’m thinking “Click” and maybe a few others) then only a nominal amount of memory is required.