Reputation: 1835
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?
Upvotes: 27
Views: 7512
Reputation: 34489
If you were to be writing data at the same time (and you were using .NET 4.0) then you could use the ConcurrentDictionary
Upvotes: 2
Reputation: 20461
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
Upvotes: 2
Reputation: 1062780
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.
Upvotes: 21