包含关键线程安全 [英] ContainsKey Thread Safe
问题描述
在以下代码中:
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)对于第一个返回缓存[key],有没有机会返回乱码?
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&缓存[key]。
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:
为了允许通过多个线程读取
来收集集合,您必须实现自己的
同步。
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 在线程安全的集合。
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.
这篇关于包含关键线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!