nw.
nw.

Reputation: 5145

Getting a lock on a single dictionary entry instead of whole dictionary?

Say I have a static Dictionary<string, object> and want to do something like the following, except I only want to lock the specific dictionary entry that I'm currently dealing with instead of the entire dictionary:


lock(myDictionary)
{
   if(myDictionary["myKey"] == null)
   {
      myDictionary["myKey"] = new MyClass();
   }
}

Is this possible without writing my own Dictionary implementation?

Thanks,

Upvotes: 0

Views: 1004

Answers (3)

Ondrej Tucny
Ondrej Tucny

Reputation: 27962

In your case it makes no sense to “lock the specific dictionary entry” only; even if you write your own implementation. If you don't know if the entry exists and you want to add it into the dictionary in such a case, you will always have to synchronize access to the dictionary's control structures. In other words, even if you implement it yourself, there will be a need to synchronize access to at least a certain portion of its internal structures.

Upvotes: 1

NightDweller
NightDweller

Reputation: 923

Try ConcurrentDictionary

Upvotes: 1

Reed Copsey
Reed Copsey

Reputation: 564333

You can use the new ConcurrentDictionary<TKey,TValue> class. It effectively provides thread safety by locking in a much finer grained manner than locking on the entire dictionary.

Upvotes: 6

Related Questions