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:
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?