Reputation: 5145
Say I have a static Dictionary
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:<string, object
>
lock(myDictionary)
{
if(myDictionary["myKey"] == null)
{
myDictionary["myKey"] = new MyClass();
}
}
Is this possible without writing my own Dictionary implementation?
Thanks,
Upvotes: 0
Views: 1004
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
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