使用ConcurrentDictionary更新字典代码

时间:2016-02-18 15:03:43

标签: c# .net multithreading concurrency concurrentdictionary

如何更新以下代码以使用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);
    }
}

2 个答案:

答案 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);