Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi-threaded access to C# dictionary

I understand that C# dictionaries are not thread-safe when it comes to adding, reading and removing elements; however, can you access the Count Property of a C# dictionary in a thread safe way if another thread is writing, reading, and removing from the dictionary?

like image 923
user809409 Avatar asked Dec 30 '25 01:12

user809409


2 Answers

Since property is a method call under the hood hood so really situation is not such simple as at first glance.

  • T1: Accessing Count property
  • T1: get_Count() call (some kind of JMP/GOTO ASM instruction)
  • T1: read variable which represents a number of items == 1
  • T2: addign a new item, real count becomes 2
  • T1: returns 1 but really there are already two items

So if an application logic relies on a Count property value - theoretically you could ends up with race condition.

like image 92
sll Avatar answered Dec 31 '25 17:12

sll


It should be threadsafe in that it won't blow up, but I'm fairly sure it is not threadsafe in that it might not give you the correct count due to other threads manipulating the dictionary.

[Edit: as usr points out, just because it's currently threadsafe at this level does not mean that it will continue to be so. You have no guarantees]

like image 33
Telastyn Avatar answered Dec 31 '25 16:12

Telastyn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!