您可以继续注销 try-catch 选项。我不知道它是否更慢,但我知道如果有另一个线程更新Dictionary,它不会总是产生正确、一致和可预测的结果。问题是,在某些时候,作者会让Dictionary 处于半生不熟的状态,并且不知道读者会看到什么。这是行不通的。
选项 1:如果您可以使用 .NET 4.0,那么我会使用 ConcurrentDictionary。
选项 2:如果您使用的是 .NET 3.5,那么您可以下载 Reactive Extensions 反向端口。 ConcurrentDictionary 包含在 System.Threading.dll 中。
选项 3: 另一个想法是保留 Dictionary 的两个单独副本。一个仅用于阅读,另一个将作为接受更新的官方副本。每当您更新“官方”Dictionary 时,您都会克隆它并覆盖副本的引用。
public class Example
{
// This is the official version which can accept updates.
private readonly Dictionary<int, CustomObject> official = new Dictionary<int, CustomObject>();
// This is a readonly copy. This must be marked as volatile for this to work correctly.
private volatile Dictionary<int, CustomObject> copy = new Dictionary<int, CustomObject>();
public class Example()
{
}
public void Set(int id, CustomObject value)
{
lock (official)
{
// Update the official dictionary.
official[id] = value;
// Now create a clone of the official dictionary.
var clone = new Dictionary<int, CustomObject>();
foreach (var kvp in official)
{
clone.Add(kvp.Key, kvp.Value);
}
// Swap out the reference.
copy = clone;
}
}
public CustomObject Get(int id)
{
// No lock is required here.
CustomObject value = null;
if (copy.TryGetValue(id, out value))
{
return value;
}
return null;
}
}
如果Dictionary中有很多项目,或者如果对官方副本的更新频繁发生,则此选项不起作用。但是,这是我不时使用的技巧。
选项 4:同样合理的方法是坚持使用普通的旧 lock。