A Handy Extension Method: Raise Events Safely

25 במאי 2009

2 תגובות

Raising events is a very common practice. We do that a lot and it’s pretty irritating to check for nullity every time:

if (eventHandler != null)
{
    eventHandler(sender, e);
}

Here comes extensions methods to our aid again. With only two extension methods, we can cover all possible event handlers and raise our events safely in one line. For example:

MyEvent.RaiseSafe(this, EventArgs.Empty);

Or

MyEvent.RaiseSafe<MyEventArgs>(this, new MyEventArgs(someParameter));

In order to achieve that, here are the needed extension methods:

public static class Extensions
{
    /// <summary>
    /// Raises the event in a safe way.
    /// </summary>
    /// <param name="eventHandler">The event handler.</param>
    /// <param name="sender">The sender.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    static public void RaiseSafe(this EventHandler eventHandler, object sender, System.EventArgs e)
    {
        if (eventHandler != null)
        {
            eventHandler(sender, e);
        }
    }

    /// <summary>
    /// Raises the event in a safe way.
    /// </summary>
    /// <typeparam name="T">Type of the event handler.</typeparam>
    /// <param name="eventHandler">The event handler.</param>
    /// <param name="sender">The sender.</param>
    /// <param name="e">The event arguments containg that event data.</param>
    static public void RaiseSafe<T>(this EventHandler<T> eventHandler, object sender, T e)
        where T : System.EventArgs
    {
        if (eventHandler != null)
        {
            eventHandler(sender, e);
        }
    }
}

All the best,

Shay

kick it on DotNetKicks.com

Shout it

הוסף תגובה
facebook linkedin twitter email

כתיבת תגובה

האימייל לא יוצג באתר. (*) שדות חובה מסומנים

2 תגובות

  1. Kelly Brown12 ביוני 2009 ב 20:29

    The article is ver good. Write please more

    להגיב
  2. Henrik (MSP)22 בספטמבר 2009 ב 0:53

    You have a race condition in your first code snippet, since another thread might have unsubscribed from the event after the nullity check. Lol @ that.

    Second, your extension method will compile into a normal static method where the event handler will be method-local which takes care of the bug. Somehow though it doesn't seem you realized this… :p

    להגיב