Category name´╝ÜAsynchronous

ForEach method exceptions and events

I just read this article by DigiMortal about List<T>.ForEach and exceptions. His assumption was that if an exception occurs while processing one of the items that the next item would still be processed which is not that case. Maybe he was aware of this (well he is now!) and somebody did not add exception handling to the method called (which by the way is not that methods responsibility IMHO).

Turns out that I had a similar problem a long time ago with events.

class Test
{
    public event EventHandler MyEvent;

    public void DoMyEvent()
    {
        if(MyEvent!=null)
        {
            MyEvent(this, EventArgs.Empty);
        }
    }
}

This example allows subscriptions to the MyEvent event. At a certain time I experienced weird application behaviour and the cause was that a subscription raised an exception causing other subscribers not receiving my precious event! As this implementation did not know how stable the subscribers were it needed a redesign and that was the following:

class Test
{
    private readonly List<EventHandler> _myEvent = new List<EventHandler>();

    public event EventHandler MyEvent
    {
        add { _myEvent.Add(value); }
        remove { _myEvent.Remove(value); }
    }

    public void DoMyEvent()
    {
        foreach (var subscriber in _myEvent)
        {
            try
            {
                subscriber.Invoke(this, EventArgs.Empty);
            }
            catch (Exception)
            {
                // Do some logging here or just BAN the subscription!
            }
        }
    }
}

This could contain some errors as I just did this from notepad but you bet the idea. The cool thing is that you can rewrite the DoMyEvent method to invoke all subscriptions simultaneously which can be very neat if they do expensive remote calls.

  • Recent Posts
  • Recent Comments
  • Archives
  • Categories
  • Meta