Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read only Dictionary - multiple threads calling .ContainsKey method

I have a static readonly dictionary. No modifications will be made to this dictionary.

I have multiple threads reading from this dictionary using the .ContainsKey(Key). e.g.

class MyData {      private static private IDictionary<int, string> _dictionary = new Dictionary<int, string>();      MyData()     {         // Load Dictionary here     }      public string GetValue(int key)     {         if (_dictionary.ContainsKey(key))         {              return _dictionary[key];            }     } } 

Are there any threading problems with doing this?

like image 918
Mark 909 Avatar asked Nov 26 '10 16:11

Mark 909


1 Answers

If nobody is mutating it: this is fine. If there were occasional edits, then perhaps look at ReaderWriterLockSlim, or (my preference) edit a snapshot/copy and swap the reference.

like image 141
Marc Gravell Avatar answered Sep 18 '22 12:09

Marc Gravell