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();
}
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With