Mark 909
Mark 909

Reputation: 1835

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?

Upvotes: 27

Views: 7512

Answers (4)

Ian
Ian

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

Dean Chalk
Dean Chalk

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

Darin Dimitrov
Darin Dimitrov

Reputation: 1038810

It is safe if you are only going to read.

Upvotes: 5

Marc Gravell
Marc Gravell

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

Related Questions