即使访问并发字典,我是否必须应用锁

Do I have to apply lock even though accessing concurrent dictionary

我在 Web 中使用静态并发字典 api 并且跨用户访问它。

我正在使用以下方法:这些方法都是线程安全的吗?或者我是否必须添加 lock(),即使它是 ConccurentDictionary

基本上,它是由跨用户访问的,因此它应该能够相应地工作,因为该字典包含每个用户的集合并且它依赖于该集合。

static ConcurrentDictionary<string, SApp> SAppFarm= new ConcurrentDictionary<string, SApp>();    

.TryRemove(_sessionUser,out s);
.TryAdd(_sessionUser, r);
.GetOrAdd(sessionUser, application);

据记载ConcurrentDictionaryhere是thread-safe。这包括 TryRemoveTryAddGetOrAdd 方法。

因此不需要锁定。请记住,线程安全涉及 keys。如果您在不同线程中为给定键更改相同的 value 对象,那么您必须关心此更改操作的 thread-safety。