string Get(string key){
lock(_sync){
// DoSomething
}
}
If DoSomething depend only on key, I want key dependent lock. I think it may be dictionary with sync objects. Is there any complete solution?
Something like real example What is the best way to lock cache in asp.net?
Well, you could create a Dictionary<string, object>
and lazily populate it with objects to lock on. For example:
readonly Dictionary<string, object> dictionary = new Dictionary<string, object>();
readonly object dictionaryLock = new object();
string Get(string key) {
object bodyLock;
lock (dictionaryLock) {
if (!dictionary.TryGetValue(key, out bodyLock)) {
bodyLock = new object();
dictionary[key] = bodyLock;
}
}
lock (bodyLock) {
...
}
}
If you need to lock in the same way elsewhere, I'd move the "lock finding" part to a helper method. Note that if you're using .NET 4, ConcurrentDictionary
can make this easier, and without the use of an extra lock.
Note that there's nothing which will ever clear the dictionary in this design... do you have a fixed set of keys (in which case that's okay) or could it grow forever?
One thing which you appear to already have realised: locking on the key itself would be a really bad idea. Equal keys could be distinct objects, and if there's any other code which locks on strings as well, it could interfere with this code. Locking on strings is almost always wrong :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With