简体   繁体   English

字典作为线程安全的变量

[英]Dictionary as thread-safe variable

I have a class (singleton) and it contains a static Dictionary 我有一个类(单例),它包含一个静态字典

private static Dictionary<string, RepositoryServiceProvider> repositoryServices = null;

in the instance of this class I populate the dictionary (can occur from multiple threads). 在这个类的实例中我填充字典(可以从多个线程发生)。 At first I had just 起初我只是

        RepositoryServiceProvider service = null; 
        repositoryServices.TryGetValue(this.Server.Name, out service);
        if (service == null) {
          service = new RepositoryServiceProvider(this.Server);
          repositoryServices.Add(this.Server.Name, service);  
        }

then I got some exceptions as Item already added so I changed it to: 然后我有一些例外,因为Item已添加,所以我将其更改为:

        RepositoryServiceProvider service = null;    
        repositoryServices.TryGetValue(this.Server.Name, out service);
        if (service == null) {
          lock (padlock) {
            repositoryServices.TryGetValue(this.Server.Name, out service);
            if (service == null) {
              service = new RepositoryServiceProvider(this.Server);
              repositoryServices.Add(this.Server.Name, service);  
            }
          }
        }

and padlock is in the class: 和挂锁在课堂上:

private static readonly object padlock = new object();

is this thread safe? 这个线程安全吗? or its overcomplicated? 还是过于复杂? or should I use ConcurentDictionary ? 或者我应该使用ConcurentDictionary

IF you can use ConcurrentDictionary - it is in several situations faster than your approach because it implements most operations lock-free while being thread-safe. 如果您可以使用ConcurrentDictionary - 它在几种情况下比您的方法更快,因为它在线程安全的同时实现了大多数无锁操作。

EDIT - as per comments: 编辑 - 根据评论:

The term "most operations lock-free" is a bit too general... “大多数操作无锁”这个词有点过于笼统......

Basically it means reduced contention ... thus in some cases more efficiency compared to a situation with one global lock, ie accessing a second bucket while the first bucket is locked works as if there was no lock from the POV of the accessing code... although that means a lock local to that bucket... in real-world applications it delivers much better performance than a global lock - esp. 基本上它意味着减少争用...因此在某些情况下与具有一个全局锁定的情况相比更高效,即在第一个存储桶被锁定时访问第二个存储桶就好像没有来自访问代码的POV的锁定一样。虽然这意味着该桶的本地锁定......在实际应用中,它提供了比全局锁定更好的性能 - 尤其是。 with multi-core. 多核。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM