相关疑难解决方法(0)

.NET - 字典锁定与ConcurrentDictionary

我找不到关于ConcurrentDictionary类型的足够信息,所以我想我会在这里问一下.

目前,我使用a Dictionary来保存由多个线程(来自线程池,因此没有确切数量的线程)不断访问的所有用户,并且它具有同步访问权限.

我最近发现在.NET 4.0中有一组线程安全的集合,它似乎非常令人愉快.我想知道,什么是"更有效和更容易管理"的选项,因为我可以选择正常Dictionary的同步访问,或者具有ConcurrentDictionary已经线程安全的选项.

参考.NET 4.0 ConcurrentDictionary

.net concurrency dictionary concurrentdictionary

121
推荐指数
6
解决办法
6万
查看次数

字典作为线程安全的变量

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

private static Dictionary<string, RepositoryServiceProvider> repositoryServices = null;
Run Code Online (Sandbox Code Playgroud)

在这个类的实例中我填充字典(可以从多个线程发生).起初我只是

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

然后我有一些例外,因为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);  
            }
          }
        }
Run Code Online (Sandbox Code Playgroud)

和挂锁在课堂上:

private static readonly object padlock = new object();
Run Code Online (Sandbox Code Playgroud)

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

c# static dictionary thread-safety

3
推荐指数
1
解决办法
3760
查看次数