Dictionary as thread-safe variable

I have a class (singleton) and it contains a static dictionary

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

      

in an instance of this class, I populate a dictionary (can arise from multiple threads). At first I 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 the item was 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);  
            }
          }
        }

      

and the padlock is in the class:

private static readonly object padlock = new object();

      

Is this thread safe? or is it more difficult? or should I use ConcurentDictionary ?

+3


source to share


1 answer


IF you can use ConcurrentDictionary

- this is faster in several situations than your approach because it implements most operations without blocking while being thread safe.

EDIT - as per the comments:



The term "most non-blocking operations" is too general ...

This basically means less contention ... so in some cases more efficiency compared to a single global blocking situation, i.e. access to the second bucket when the first carpet is blocked, works as if there were no blocking from POV access code ... although this means that the local location of this bucket ... in real applications it provides much better performance than the global locking - esp. with a multi-core processor.

+8


source







All Articles