Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EventAggregator, is it thread-safe?

Is this thread-safe?

The EventAggregator in Prism is a very simple class with only one method. I was surprised when I noticed that there was no lock around the null check and creation of a new type to add to the private _events collection. If two threads called GetEvent simultaneously for the same type (before it exists in _events) it looks like this would result in two entries in the collection.

    /// <summary>
    /// Gets the single instance of the event managed by this EventAggregator. Multiple calls to this method with the same <typeparamref name="TEventType"/> returns the same event instance.
    /// </summary>
    /// <typeparam name="TEventType">The type of event to get. This must inherit from <see cref="EventBase"/>.</typeparam>
    /// <returns>A singleton instance of an event object of type <typeparamref name="TEventType"/>.</returns>
    public TEventType GetEvent<TEventType>() where TEventType : EventBase
    {
        TEventType eventInstance = _events.FirstOrDefault(evt => evt.GetType() == typeof(TEventType)) as TEventType;
        if (eventInstance == null)
        {
            eventInstance = Activator.CreateInstance<TEventType>();
            _events.Add(eventInstance);
        }
        return eventInstance;
    }
like image 501
pfaz Avatar asked May 14 '10 12:05

pfaz


People also ask

What is EventAggregator?

An Event Aggregator acts as a single source of events for many objects. It registers for all the events of the many objects allowing clients to register with just the aggregator.

What is EventAggregator in prism?

What is Prism EventAggregator? In short, EventAggregator is Prism's implementation of the Publisher-Subscriber pattern. Publisher-Subscriber is a messaging pattern designed to facilitate asynchronous communication in your application.

What is event aggregator WPF?

The Prism Library provides an event mechanism that enables communications between loosely coupled components in the application. This mechanism, based on the event aggregator service, allows publishers and subscribers to communicate through events and still do not have a direct reference to each other.


1 Answers

No, not thread safe.

  1. The instance member access of the List class itself are NOT thread safe, as per MSDN under Thread safety
  2. The method itself is not thread safe
    1. 2 threads could enter the method at the same time
    2. Both try to get the FirstOrDefault
    3. Both get nothing
    4. Both add a new TEventType

I would

  1. switch to one of the System.CollectionConcurrentX collections in .NET 4
    http://msdn.microsoft.com/en-us/library/system.collections.concurrent.aspx
    or
  2. do your own locking
like image 93
Peter Gfader Avatar answered Oct 03 '22 06:10

Peter Gfader