MBe*_*ius 8 c# multithreading dictionary
在以下代码中:
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";
}
}
Run Code Online (Sandbox Code Playgroud)
1)ContainsKey线程是否安全?IOW,如果在另一个线程向字典中添加内容时执行该方法会发生什么?2)对于第一个返回缓存[key],是否有可能返回乱码值?
TIA,
MB
Mic*_*ael 14
ContainsKey固有的线程安全无关紧要,因为ContainsKey和cache [key]之间没有同步.
例如:
if (cache.ContainsKey(key))
// Switch to another thread, which deletes the key.
return cache[key];
Run Code Online (Sandbox Code Playgroud)
MSDN在这一点上非常明确:
要允许多个线程访问集合以进行读写,您必须实现自己的同步.
有关更多信息,JaredPar 在线程安全的http://blogs.msdn.com/jaredpar/archive/2009/02/11/why-are-thread-safe-collections-so-hard.aspx上发布了一篇很棒的博客文章集合.
不,如果您在尝试阅读时写入值,则ContainsKey不是线程安全的.
是的,你有可能找回无效的结果 - 但你可能会先开始看异常.
看看ReaderWriterLockSlim是否锁定了这样的情况 - 它是为了做这种事情而构建的.