【发布时间】:2010-12-09 16:00:01
【问题描述】:
我注意到 GetOrAdd() 总是执行工厂委托,即使该值存在于字典中。例如:
class Program
{
private static ConcurrentDictionary<string, string> _cache = new ConcurrentDictionary<string, string>();
static void Main(string[] args)
{
string value;
value = GetValueFromCache("A"); // cache is empty, CacheValueFactory executes, A is added
value = GetValueFromCache("A"); // cache contains A, CacheValueFactory executes
value = GetValueFromCache("C"); // cache contains A, CacheValueFactory, C is added
value = GetValueFromCache("A"); // cache contains A and C, CacheValueFactory executes
}
private static string GetValueFromCache(string key)
{
string val = _cache.GetOrAdd(key, CacheValueFactory(key));
return val;
}
private static string CacheValueFactory(string key)
{
if (key == "A")
return "Apple";
else if (key == "B")
return "Banana";
else if (key == "C")
return "Cherry";
return null;
}
}
在第一次调用 GetValueFromCache("A") 时,缓存为空并添加了 A:Apple。使用调试器时,我注意到在第二次和第三次调用 GetValueFromCache("A") 时,总是执行 CacheValueFactory() 方法。这是预期的吗?我会认为如果字典中存在密钥,则委托方法不会执行。
【问题讨论】:
标签: c# multithreading .net-4.0