Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ConcurrentDictionary is it threadsafe to edit the value after a GetOrAdd?

I am using the GetOrAdd method of the concurrent dictionary to retrieve a list of values then with a reference to that list of values I'm editing them. Is it thread-safe to do it this way?

The first method I'm adding a value and the second method I'm clearing the list.

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();
        }
    }
}
like image 510
Evan Larsen Avatar asked Apr 29 '14 20:04

Evan Larsen


1 Answers

The dictionary provides no protection for the value stored. The only thing it manages is ensuring that the mapping of keys to values remains consistent. You still need to protect the data of the objects stored with appropriate locking.

like image 60
Dark Falcon Avatar answered Oct 25 '22 14:10

Dark Falcon