Asynchronous Events

The most common use for delegates in .NET is for event subscription and publishing. Example 7-12 contains a simple definition of an event publisher and subscriber.

Example 7-12. Event publisher and subscriber, using synchronous event publishing

using NumberChangedEventHandler = GenericEventHandler<int>;

public class MyPublisher
{
   public event NumberChangedEventHandler NumberChanged;
   public void FireEvent(int number)
   {
      if(NumberChanged != null)
      {
         NumberChanged(number);
      }
   }
}
public class MySubscriber
{
   public void OnNumberChanged(int number)
   {...}
}

Consider the following client code, which hooks subscribers to the publisher and fires the event:

    MyPublisher  publisher   = new MyPublisher();
    MySubscriber subscriber1 = new MySubscriber();
    MySubscriber subscriber2 = new MySubscriber();

    publisher.NumberChanged += subscriber1.OnNumberChanged;
    publisher.NumberChanged += subscriber2.OnNumberChanged;
    publisher.FireEvent(3);

When a publisher fires an event, it’s blocked until all the subscribers have finished handling the event, and only then does control return to the publisher. Disciplined and well-behaved subscribers should not perform any lengthy operations in their event-handling method, because that prevents other subscribers from handling the event (not to mention blocking the publisher). The problem is, how does the publisher know if it’s dealing with disciplined subscribers? The reality is, of course, that the publisher can’t tell. The publisher must therefore defensively ...

Get Programming .NET Components, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.