Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread Safety with Dictionary

If I have a

Dictionary<int, StreamReader> myDic = new Dictionary<int, StreamReader>
//Populate dictionary

One thread does

myDic[0] = new StreamReader(path);

Another thread does

myDic[1] = new StreamReader(otherpath)

Is this thread safe because the actual item in the dictionary getting modified is different to the one on the other thread or will I get a InvalidOperationException: Collection was modified

like image 497
Jon Avatar asked Nov 18 '11 13:11

Jon


People also ask

Is Dictionary in python thread-safe?

Most Dictionary Operations Are AtomicMany common operations on a dict are atomic, meaning that they are thread-safe.

Is Dictionary Trygetvalue thread-safe?

Not only is it not thread safe; it will also throw with NullReferenceException if accessed while another thread is reorganizing the hash buckets. The lock statement is wicked fast, don't avoid it.

Is Dictionary in Swift thread-safe?

Dictionaries in Swift are not thread safe , they lead to wierd crashes which are very hard to debug. This class solves this problem by using a dictionary whose accesses are made thread safe by using a concurrent queue with a barrier.


1 Answers

You will only get InvalidOperationException: Collection was modified if you enumerate the dictionary while modifying.

However, that is not thread-safe.
If one of those operations causes the dictionary to resize, the other one may get lost.
Instead, use ConcurrentDictionary.

like image 195
SLaks Avatar answered Sep 19 '22 13:09

SLaks