I have been building ASP.NET MVC application and I’m worried about potential multi-threading issues when I launch it. One particular concern is the following code:
private static IDictionary<string, ISettings> _settingsDictionary = new Dictionary<string, ISettings>();
public T Settings<T>() where T : ISettings, new() {
var key = typeof(T).FullName;
if (!_settingsDictionary.ContainsKey(key))
_settingsDictionary[key] = _settingsService.GetSettings<T>();
return (T)_settingsDictionary[key];
}
Notice the dictionary is defined as static. This allows me to cache the dictionary so that it returns the same instance for every request for the length of the application.
This works fine when testing locally but i’m worried it may suffer when used by hundreds of users. This has led me to investigate the ConcurrencyDictionary. Please could you advise me on whether I need to use it and how i would go about doing so if that is the case.
Thanks
Yes there is a potential data race here:
which could cause two threads to add the same key, since they can be interrupted at any point.
You could use ConcurrentDictionary.GetOrAdd instead:
Edit: Since you don’t want
_settingsService.GetSettings<T>()to be executed every time, an alternative could be: