如何更新以下代码以使用ConcurrentDictionary?
private Dictionary (string, SymbolOrderBook) books = new Dictionary(string, SymbolOrderBook)();
SymbolOrderBook book;
lock (books)
{
if (!books.TryGetValue(symbol, out book))
{
book = new SymbolOrderBook(symbol);
books.Add(symbol, book);
}
}
答案 0 :(得分:2)
您可以使用GetOrAdd
方法,如下所示:
首先,您可以像这样定义字典:
private ConcurrentDictionary<string, SymbolOrderBook> books =
new ConcurrentDictionary<string, SymbolOrderBook>();
然后你得到或添加这样的条目:
SymbolOrderBook book = books.GetOrAdd(symbol, s => new SymbolOrderBook(s));
这样做是它返回一个现有的书,如果它存在于指定的符号,或者,它创建一个新的,将它添加到字典,然后返回它。所有这些都发生在原子操作中。
答案 1 :(得分:1)
using System.Collections.Concurrent;
ConcurrentDictionary<string, SymbolOrderBook> books = new ConcurrentDictionary<string, SymbolOrderBook>();
SymbolOrderBook book = new SymbolOrderBook(symbol);
books.GetOrAdd(symbol, book);