In the .NET Framework, there is Dictionary
and ConcurrentDictionary
.
These provide method like Add
, Remove
, and so on...
I know when we design a multi-thread program, we use ConcurrentDictionary
to replace Dictionary
for thread-safety.
I wonder why ConcurrentDictionary
has AddOrUpdate
, GetOrAdd
and similar methods, while Dictionary
has not.
We always like below code to get object from a Dictionary
:
var dict = new Dictionary<string, object>();
object tmp;
if (dict.ContainsKey("key"))
{
tmp = dict["key"];
}
else
{
dict["key"] = new object();
tmp = new object();
}
but when using ConcurrentDictionary
, similar code is just one line only.
var conDict = new ConcurrentDictionary<string, object>();
var tmp = conDict.GetOrAdd("key", new object());
I expect .NET to have those methods, but why it doesn't?