1

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.

Dim_Ka
  • 788
  • 1
  • 7
  • 26

1 Answers1

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
  • 1
    Can 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