I have a doubt with the concurrent dictionary in C#.
In another question I was asked how to have a concurrent dictionary with a hashset as value, but it isn't a good idea to work with a hashset, it is better to use a concurrent dictionary as value. So the solution that I get was this:
var myDic = new ConcurrentDictionary<long, ConcurrentDictionary<int, byte>>();
myDic.AddOrUpdate(key,
_ => new ConcurrentDictionary<int, byte>(new[] {new KeyValuePair<int, byte>(element, 0)}),
(_, oldValue) => {
oldValue.TryAdd(element, 0);
return oldValue;
});
Suppose that I have two threads, where "element" is 1 in the thread A and 2 in the thread B.
My doubt is if this is thread safe. I can be wrong but I think that the concurrent dictionary works in this way:
Thread A: try to insert element 1 for key 1. The key 1 doesn't exist, so it try to insert the key 1 with the concurrent dictionary ConcurrentDictionary<int, byte>(new[] {new KeyValuePair<int, byte>(1, 0)
.
Thread B: tries to insert the item 2 in the dictionary of key 1. Thread A is still adding the new key/value, Thread B thinks that key 1 doesn't exists, so try to add the value ConcurrentDictionary<int, byte>(new[] {new KeyValuePair<int, byte>(2, 0)
to the key 1.
Thread A finishes to insert the key/value pair successfully.
Thread B tries to finish, but now it the key 1 exists because thread A inserted the key 1. So the thread B can't insert the key/value.
So what happen? The work of thread B is discard so I will only have one item in the concurrent dictionary for the key 1? Or perhaps thread B enters in the updateValueFactory
and add the item 2 to the dictionary?