这是线程安全的吗?EventAggregator,它是线程安全的吗?
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;
}
+1 @Peter同意。在遇到一些问题后,我来到这里进行完整性检查,然后在反射器中查看EventAggregator的代码。考虑到预期的建筑使用情况,我无法相信它们不会使其线程安全。反正我很惊讶。 – 2010-09-15 13:00:00
@chibacity我也很惊讶我是;-) – 2010-09-20 04:00:41