gpt4 book ai didi

wpf - EventAggregator,它是线程安全的吗?

转载 作者:行者123 更新时间:2023-12-01 19:43:51 25 4
gpt4 key购买 nike

这是线程安全的吗?

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

最佳答案

不,不是线程安全的。

  1. List 类本身的实例成员访问非线程安全,根据MSDN under Thread safety
  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. 自己进行锁定

关于wpf - EventAggregator,它是线程安全的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2834035/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com