-1

How to update the following code to use a 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);
    }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
pollardo
  • 41
  • 4
  • And what are you struggling with that is stopping you from doing it yourself? Also we can't convert that because that is not valid code. For example is `book` local to the function or is it a class level varible? Please show the method declration. – Scott Chamberlain Feb 18 '16 at 15:05
  • 1
    Take a look at the [GetOrAdd](https://msdn.microsoft.com/en-us/library/ee378676%28v=vs.110%29.aspx) method. – Yacoub Massad Feb 18 '16 at 15:34

2 Answers2

3

You can use the GetOrAdd method like this:

First, you define the dictionary like this:

private ConcurrentDictionary<string, SymbolOrderBook> books =
    new ConcurrentDictionary<string, SymbolOrderBook>();

And then you get or add an entry like this:

SymbolOrderBook book = books.GetOrAdd(symbol, s => new SymbolOrderBook(s));

What this does is that it either returns an existing book if it exists for the specified symbol, or else, it creates a new one, adds it to the dictionary, and then returns it. All that happens in an atomic operation.

Yacoub Massad
  • 27,509
  • 2
  • 36
  • 62
1
using System.Collections.Concurrent;

ConcurrentDictionary<string, SymbolOrderBook> books = new ConcurrentDictionary<string, SymbolOrderBook>();
SymbolOrderBook book = new SymbolOrderBook(symbol);
books.GetOrAdd(symbol, book);
nobody
  • 10,892
  • 8
  • 45
  • 63
  • 1
    Personally I would use the overload that takes in a `Func` that way you are not creating a new book unless you need to. Also it is not clear from the OP's code if `book` is used later on in the code, your current answer would make `book` be a new value every time and would never get the stored value. – Scott Chamberlain Feb 18 '16 at 15:46