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();
}
}
}