tags:

views:

63

answers:

1

I am using a plugin system on an ASP.NET MVC application I am working on (loosely based on Rob Connery's MVC storefront project implementation).

In addition to executing plugin methods, I also want to allow classes to provide various event hooks that a plugin can subscribe to.

I am publishing my events like so:

        #region Events

    public static event ItemAddedEventHandler ItemAdded;
    internal virtual void OnItemAdded(EventArgs e)
    {
        if (ItemAdded != null)
            ItemAdded(this, new EventArgs());
    }

    public static event LineRemovedEventHandler LineRemoved;
    internal virtual void OnLineRemoved(EventArgs e)
    {
        if (LineRemoved != null)
            LineRemoved(this, new EventArgs());
    }

    #endregion

    public delegate void ItemAddedEventHandler(object sender, EventArgs e);
    public delegate void LineRemovedEventHandler(object sender, EventArgs e);

And an example plugin:

        public EventHooks() {
        Cart.ItemAdded += new Cart.ItemAddedEventHandler(Cart_ItemAdded);
        Cart.LineRemoved += new Cart.LineRemovedEventHandler(Cart_LineRemoved);
    }

    void Cart_ItemAdded(object sender, EventArgs e) {
        _loggerService.Info("An item was added to the cart.");
    }

    void Cart_LineRemoved(object sender, EventArgs e) {
        _loggerService.Info("A line was removed from the cart.");
    }

Is this a good and thread safe way of publishing and subscribing to these events?

Any thoughts or suggestions appreciated.

Thanks Ben

+3  A: 

Assign your EventHandler's to a local var before firing them.

ItemAddedEventHandler handler = ItemAdded;

if (handler != null) 
{
   handler(this, EventArgs.Empty) 
}

There is a race condition between checking the null and firing the event. You'd better follow the guidelines anyhow.

Maxwell Troy Milton King
I'm just curios because I want to learn something, why is this any different or better? Can you update your answer to include why?
jsmith
Sure, sorry for that.
Maxwell Troy Milton King
great, thanks for this. Did see this article but missed the point about the race condition.
Ben