Creating types with lots of events

Matt Burseth recently posted about his discovering the System.ComponentModel.EventHandlerList class while disassembling the Control class.

So, what's the point of this class?  If you think about events, you normally think "awesome."  Something in your object happens, you inform other objects about what just happened, and they do stuff with this information.  Its a sweet wrapper around delegate swapping.  But there are some things you have to take into consideration with events.  First, they require code.  Code you never see.  When your event is compiled into IL, it is transformed into a private delegate field, and a property containing add_eventname and remove_eventname methods. 

That means that objects that have lots of events, such as System.Windows.Forms.Control and its 69 public events, most of which are never used, waste lots of memory.  And since just about everything in the UI of a Windows Form is a Control, you're potentially talking about lots of wasted memory that puts unneeded pressure on the GC. 

The EventHandlerList is a way to get around wasting this memory.  Event delegates are not created until someone registers interest in them.  That's what the EventHandlerList does--it keeps track of event delegates, adding new registrants to existing delegates and creating new ones when needed.  But there are two things you must understand about this class.

First, it is implemented as a linked list.  So event access is, in a worst case situation O(n), where n is the number of events already registered.  If you have a thousand events and expect registrations to come in very quickly, that could show up as a performance hit.  Will that ever happen?  No.  Pretty much no.  But why waste time with a slow-ass linked list when the collection could be managed with a hashtable and get O(1) access times?

Second thing to consider, and probably the most important one, is that the EventHandlerList is not thread safe.  At all.  If you use it, you are responsible for managing how two or more threads access this object at the same time.  Sucks to be you.

Jeffrey Richter supposedly has an "EventSet" object that addresses these two issues, however it (and him) are AWOL on the subject.  You can go buzz around his blog and website to see if its there.

Anyhow, that's the dope on the EventHandlerList object.  Gotta go to another friggen meeting.  Bye for now...


Programming Post by: McGurk at 01:07 PM | Reply
Kick this post:

Press butan, recieve imagelet. Hover for preview. Imagelets are pasted at the end of your comment. Think ahead.

Comments are disabled. Post is locked.