【问题标题】:ConcurrentDictionary is it threadsafe to edit the value after a GetOrAdd?ConcurrentDictionary 在 GetOrAdd 之后编辑值是否线程安全?
【发布时间】:2014-04-29 20:27:39
【问题描述】:

我正在使用并发字典的 GetOrAdd 方法来检索值列表,然后参考我正在编辑的值列表。这样做是线程安全的吗?

第一种方法是添加值,第二种方法是清除列表。

using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading.Tasks;
using Test.Web.Services;

namespace Test.Web.Messaging
{
    public class Dispatch
    {
        private static readonly ConcurrentDictionary<string, IList<Message>> Messages = new ConcurrentDictionary<string, IList<Message>>();

        public static void AddMessage(string id, Message value)
        {
            var msgs = Messages.GetOrAdd(id, new List<Message>());
            msgs.Add(value);
        }

        public static void Send(string id)
        {
             var msgs = Messages.GetOrAdd(id, new List<Message>());
             foreach (var msg in msgs)
             {
                 Connection.Send(id, msg);
             }
             msgs.Clear();
        }
    }
}

【问题讨论】:

    标签: c# thread-safety task-parallel-library concurrentdictionary


    【解决方案1】:

    字典不为存储的值提供保护。它唯一管理的是确保键到值的映射保持一致。您仍然需要使用适当的锁定来保护存储的对象的数据。

    【讨论】:

    • ConcurrentDictionary 上的 AddOrUpdate 方法怎么样?更新委托是线程安全的吗?
    • 没有。在锁中不会调用添加或更新委托。
    【解决方案2】:

    ConcurrentDictionary 使得 value 对象线程的获取和添加是安全的。一旦获得value 对象,多个线程访问或更改同一object 的属性就不是线程安全的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-27
      • 2019-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多