-1

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?

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
AngryHacker
  • 59,598
  • 102
  • 325
  • 594
  • i cant see why it wouldnt be OK. Concurrent Dict says that it can be used wherever IDictionary can - it says so by implementing that interface. – pm100 Sep 05 '17 at 18:02
  • 4
    "Safe" under what operations? Is your program adding those keys on one thread and reading from them on another thread? Do you have an ordering requirement that the reader run after the writer? Because those invariants are not maintained by your code. The concurrent dictionary **will not crash your process** under a race condition, but that doesn't mean that your program is automatically *correct*! You are required to treat the dictionary as *constantly changing* unless you have written code that keeps it still. – Eric Lippert Sep 05 '17 at 18:02
  • @EricLippert Not those same keys and I have ordering instructions. Other threads do add or edit keys, but not the ones in this method. – AngryHacker Sep 05 '17 at 18:04

1 Answers1

2

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.

Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357