问题描述
在下面的代码:
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)对于第一个回缓存[键],是否有任何机会,它可以返回一个值乱码?
1) Is ContainsKey thread safe? IOW, what happens if that method is executing when another thread is adding something to the dictionary?2) For the first return cache[key], is there any chance that it could return a garbled value?
TIA,
MB
推荐答案
的containsKey固有的线程安全性并不重要,因为没有的containsKey与放大器之间没有同步; 。缓存[关键]
The inherent thread safety of ContainsKey doesn't matter, since there is no synchronization between ContainsKey & cache[key].
例如:
if (cache.ContainsKey(key))
// Switch to another thread, which deletes the key.
return cache[key];
MSDN是在这一点上很清楚的:
MSDN is pretty clear on this point:
要允许集合多个线程读取和
书面访问
,你必须实现自己的
同步。
有关更多信息,JaredPar张贴在的对线程安全的集合。
For more info, JaredPar posted a great blog entry at http://blogs.msdn.com/jaredpar/archive/2009/02/11/why-are-thread-safe-collections-so-hard.aspx on thread-safe collections.
这篇关于中的containsKey线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!