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>();
开发者_如何学JAVA MyData()
{
// Load Dictionary here
}
public string GetValue(int key)
{
if (_dictionary.ContainsKey(key))
{
return _dictionary[key];
}
}
}
Are there any threading problems with doing this?
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.
It is safe if you are only going to read.
if all of the 'adding' is complete before you read from multiple threads then it is fine. Just because its readonly doesnt mean its thread safe - which it isnt.
Maybe you should user ReaderWriterLock
to synchronise access
If you were to be writing data at the same time (and you were using .NET 4.0) then you could use the ConcurrentDictionary
精彩评论