Reputation: 3359
I use a static concurrent dictionary in web api and it is accessed by across the users.
I am using the methods below: Are these methods all thread safe? Or do I have to add lock()
even though it is ConccurentDictionary
?
Basically, it is accessed by across the user then it should able to work accordingly as this dictionary contain the collection for each user and it relies on that.
static ConcurrentDictionary<string, SApp> SAppFarm= new ConcurrentDictionary<string, SApp>();
.TryRemove(_sessionUser,out s);
.TryAdd(_sessionUser, r);
.GetOrAdd(sessionUser, application);
Upvotes: 1
Views: 2035
Reputation: 15415
The ConcurrentDictionary
is it is documented here is thread-safe. This includes the TryRemove
, TryAdd
and GetOrAdd
methods.
Therefore no locking is required. Please keep in mind, that thread safety regards the keys. If you change the same value object for a given key in different threads, then you have to care for the thread-safety of this change operation.
Upvotes: 7