I have a c# dictionary in a multithreaded environment. I'm using TryGetValue for reading without lock and in the same moment the dictionary is reorganizing. Is it possible to get a completly different value not related to this key? I mean not just a value that is not up-to-date but a value that is totaly wrong corresponding to a different key.
Asked
Active
Viewed 314 times
1
-
7Show your work first. – Soner Gönül Oct 21 '15 at 08:33
-
Multithreaded and without lock? Yes, anything can happen. Count yourself lucky the machine didn't blow up. – Corak Oct 21 '15 at 08:37
-
@Corak if it's not a web application, don't ignore app domain isolation etc. – Mathematics Oct 21 '15 at 08:38
-
@Mathematics - I stand by "anything can happen". To quote [Eric Lippert](http://stackoverflow.com/questions/19593157/this-is-thread-safe-right/19593297#19593297): "Just take the lock." – Corak Oct 21 '15 at 08:43
-
1It completely depends on the code... – Mathematics Oct 21 '15 at 08:44
1 Answers
3
Short answer: yes!
Long answer: The dictionary is not thread safe by default. If you need a thread safe one, you can use the ConcurrentDictionary
https://msdn.microsoft.com/en-us/library/dd287191(v=vs.110).aspx
Also have a look at the Microsoft reference on thread safe collections https://msdn.microsoft.com/en-us/library/dd997305(v=vs.110).aspx

DerApe
- 3,097
- 2
- 35
- 55
-
1Can you back this up? I know that `List` throws an error if the collection is modified while iterating it - are you sure that Dictionary doesn't do anything similar? – default Oct 21 '15 at 09:00
-
@Default The behavior you are describing does happen for `List` as well as for `Dictionary` but it is not directly related to the thread safe access - these are two different things which "may" end up in the same error/exception. But I understood Dim_Ka's question in a more general way – DerApe Oct 21 '15 at 10:40