字典为线程安全变量 [英] Dictionary as thread-safe variable

查看:119
本文介绍了字典为线程安全变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类(单例),它包含一个静态字典

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);  
        }

然后我有一些例外,因为Item已经添加,所以我更改为: / p>

then I got some exceptions as Item already added so I changed it to:

        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);  
            }
          }
        }

和挂锁在类中:

private static readonly object padlock = new object();

这个线程是否安全?还是其过于复杂?或者我应该使用 ConcurentDictionary

is this thread safe? or its overcomplicated? or should I use ConcurentDictionary?

推荐答案

如果您可以使用 ConcurrentDictionary - 它在几种情况下比您的方法更快,因为它在线程安全的情况下实现大多数操作无锁。

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.

编辑 - 根据评论:

术语大多数操作无锁有点太笼统了...

The term "most operations lock-free" is a bit too general...

基本上这意味着减少的争用...因此在某些情况下,与一个全局锁定的情况相比,更有效率,即在第一个桶被锁定时访问第二个桶,就像在没有锁定访问代码的POV ...虽然这意味着该桶的本地锁...在现实世界的应用程序中,它提供比全局锁更好的性能 - 尤其是。与多核。

Basically it means reduced contention ... thus in some cases more efficiency compared to a situation with one global lock, i.e. 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. with multi-core.

这篇关于字典为线程安全变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆