ConcurrentDictionary.GetOrAdd Always Executes Delegate Method ConcurrentDictionary.GetOrAdd Always Executes Delegate Method multithreading multithreading

ConcurrentDictionary.GetOrAdd Always Executes Delegate Method


The reason you're seeing this is that you are not passing CacheValueFactory as a delegate but instead evaluating the function promptly and passing the resulting value. This causes you to use the overload which accepts a key and value and not the one which accepts a key and delegate.

To use the delegate version switch the code to the following

string val = _cache.GetOrAdd(key, CacheValueFactory);


If you want to handle slightly more complicated scenarios, for example, when the parameter doesn't match the key, you could use a lambda.

        var keyStr = string.Format("Something_{0}", key);        string val = _cache.GetOrAdd(keyStr,_ => CacheValueFactory(key));