在下面的代码中:
public class StringCache
{
private readonly object lockobj = new object();
private readonly Dictionary<int, string> cache = new Dictionary<int, string>();
public string GetMemberInfo(int key)
{
if (cache.ContainsKey(key))
return cache[key];
lock (lockobj)
{
if (!cache.ContainsKey(key))
cache[key] = GetString(key);
}
return cache[key];
}
private static string GetString(int key)
{
return "Not Important";
}
}
1) ContainsKey 线程安全吗? IOW,如果当另一个线程正在向字典中添加内容时该方法正在执行,会发生什么情况? 2) 第一次返回cache[key],有没有可能返回乱码?
TIA,
MB
最佳答案
ContainsKey 的内在线程安全性无关紧要,因为 ContainsKey 和缓存 [key] 之间没有同步。
例如:
if (cache.ContainsKey(key))
// Switch to another thread, which deletes the key.
return cache[key];
MSDN 在这一点上非常清楚:
To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization.
有关更多信息,JaredPar 在 http://blogs.msdn.com/jaredpar/archive/2009/02/11/why-are-thread-safe-collections-so-hard.aspx 上发布了一篇很棒的博客条目关于线程安全的集合。
关于c# - ContainsKey线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/710696/