EventAggregator,它是线程安全的吗?

pfa*_*faz 6 silverlight wpf prism eventaggregator

这是线程安全的吗?

Prism中的EventAggregator是一个非常简单的类,只有一个方法.当我注意到null检查没有锁定并创建一个新类型以添加​​到private _events集合时,我感到很惊讶.如果两个线程同时为同一类型调用GetEvent(在_events中存在之前),则看起来这将导致集合中的两个条目.

    /// <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;
    }
Run Code Online (Sandbox Code Playgroud)

Pet*_*der 4

不,不是线程安全的。

  1. List 类本身的实例成员访问不是线程安全的,根据MSDN 的线程安全
  2. 方法本身不是线程安全的
    1. 2个线程可以同时进入该方法
    2. 两者都尝试获取 FirstOrDefault
    3. 双方都一无所获
    4. 两者都添加了新的 TEventType

我会

  1. 切换到 .NET 4 中的 System.CollectionConcurrentX 集合之一
    http://msdn.microsoft.com/en-us/library/system.collections.concurrent.aspx
  2. 自己锁定