Question

A few years ago, I read a book that described how you could override the default event 'dispatcher' implementation in .NET with your own processor.

    class foo {
       public event EventHandler myEvent;
       ...
    }

    ...
      myFoo.myEvent += myBar1.EventHandler;
      myFoo.myEvent += myBar2.EventHandler;

Whenever the event fires, both myBar1 and myBar2 handlers will be called.

As I recall, the default implementation of this loop uses a linked list and simply iterates over the list and calls the EventHandler delegates in order.

My question is two fold:

  1. Does someone know which book I was reading?
  2. Why would you want to override the default implementation (which might be answered in the book)?

Edit: The book I was referring to was indeed Jeffrey Richter's CLR via C#

Was it helpful?

Solution

It could have been one of many books or web articles.

There are various reasons why you might want to change how events are subscribed/unsubscribed:

  • If you have many events, many of which may well not be subscribed to, you may want to use EventHandlerList to lower your memory usage
  • You may wish to log subscription/unsubscription
  • You may wish to use a weak reference to avoid the subscriber's lifetime from being tied to yours
  • You may wish to change the locking associated with subscription/unsubscription

I'm sure there are more - those are off the top of my head :)

EDIT: Also note that there's a difference between having a custom way of handling subscription/unsubscription and having a custom way of raising the event (which may call GetInvocationList and guarantee that all handlers are called, regardless of exceptions, for example).

OTHER TIPS

I seem to remember something similar in Jeffrey Richter's CLR via C#. Edit: I definitely do remember that he goes into detail about it.

There are a few different reasons for taking control of event registration. One of them is to reduce code bloat when you've got TONS of events. I think Jeffrey went into this in detail within the book...

  1. No
  2. You might, for example, need to break the call chain based on the result of one of the handlers. Say your CustomEventArgs object has a property 'Blocked', which when set to true suppresses all further event handler invocations.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top