Is it safe to pass ConcurrentDictionary type into a function that takes IDictionary?

346 views Asked by At

I have a method:

void foo(IDictionary<string, object> data) {
    data["key1"] = getValue1();
    data["key2"] = getValue2();
}

I currently call it as follows:

var serialDict = new Dictionary<string, object>();
foo(serialDict);

Now I need to call foo with a ConcurrentDictionary type because the dictionary is being populated on multiple threads.

var concurrentDict = new Dictionary<string, object>();
foo(concurrentDict);

Since ConcurrentDictionary implements IDictionary, I do not have to change the signature of the foo method. And the change seems to work fine on my machine.

However, something doesn't sit well with me about being able to populate a regular dictionary and a concurrent dictionary in the same manner/method.

Is what I am doing safe?

1

There are 1 answers

0
Titian Cernicova-Dragomir On BEST ANSWER

It depends on what you do, in the method, if you just modify the dictionary using the indexing operation, it should be fine as the semantic of indexing setting is add or update and the dictionary should do this in a thread safe manner. If your method does more complicated things such as checking for the existence of a key and then adding a value if it does not exist, then that might result in unexpected results if multiple threads are writing to the dictionary (ConcurrentDictionary has dedicated overloads for add or create value, that are atomic)

Your method may also get confused if it adds to the dictionary and then expects to read the value from the dictionary and another thread modifies the same key.

So the short answer is, generally is should be fine but you need to analize your method for concurrency issues if the method was not created with thread safety in mind.