dsi
dsi

Reputation: 3359

Do I have to apply lock even though accessing concurrent dictionary

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

Answers (1)

Ralf B&#246;nning
Ralf B&#246;nning

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

Related Questions