How lock by method parameter?

故事扮演 提交于 2019-11-29 18:29:51

问题


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?


回答1:


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 :)



来源:https://stackoverflow.com/questions/4954626/how-lock-by-method-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!