I have a scenario where all the threads will only insert unique keys into the dictionary. In other words, no two threads will insert the same key. I do not have any update or read operations as well. It's only inserts. Do I need a ConcurrentDictionary
in this case?
Asked
Active
Viewed 1,744 times
1

dev27
- 605
- 1
- 7
- 15
-
1What's the point of having it if there are no update or read operations??? And, if there are update or read operations, you already know that you need a ConcurrentDictionary. – Nisarg Shah Jan 19 '18 at 17:53
-
4`A non-threadsafe collection does not come with any such guarantees. For instance, if you add something to a binary tree on one thread, while another thread is busy rebalancing the tree, there's no guarantee the item will be added, or even that the tree is still valid afterwards, it might be corrupt beyond hope.` - from the answer on linked question. – Nisarg Shah Jan 19 '18 at 17:56
-
None of the scenarios mentioned in the link provided are applicable to me. I am only inserting keys, not reading, updating or removing. I need a dictionary because every key is associated with some value. And I guess adding to a dictionary will not need any kind of data structure balancing? Sorry if I am wrong. – dev27 Jan 19 '18 at 18:11
-
@vmzi It gives you your answer right here, "A non-threadsafe collection does not come with any such guarantees. For instance, if you add something to a binary tree on one thread, while another thread is busy rebalancing the tree, there's no guarantee the item will be added, or even that the tree is still valid afterwards, it might be corrupt beyond hope." Or you could of course just look at the documentation for the type, because it's very explicit about it's thread safety guarantees. – Servy Jan 19 '18 at 18:18
-
@dev27 If you're not reading the dictionary at some point, then just throw away the values, rather than trying to store them. Problem solved! – jpaugh Jan 19 '18 at 20:11
1 Answers
6
No, it's not safe to use Dictionary
as that is implemented as a hash table. Therefore when you add a new, unique key, the add method may start rehashing the whole dictionary. If another thread concurrently tries to add another key while the rehashing is taking place, you can end up with an inconsistent data structure. So you have to use a ConcurrentDictionary in your case. See also Microsoft's advice When to use a thread-safe collection.

DodgyCodeException
- 5,963
- 3
- 21
- 42