这是线程安全的吗?
Prism 中的 EventAggregator 是一个非常简单的类,只有一个方法。当我注意到空检查和创建新类型以添加到私有 _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;
}