如何通过锁定方法的参数? [英] How lock by method parameter?

查看:177
本文介绍了如何通过锁定方法的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

string Get(string key){
   lock(_sync){
    //   DoSomething
   }
}

如果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?

喜欢的东西真实的例子
什么是asp.net锁定缓存的最佳方法是什么?

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) {
        ...
    }
}

如果您需要以同样的方式来锁定其他地方,我会移动锁定的发现的一部分,以一个辅助方法。请注意,如果你使用.NET 4, ConcurrentDictionary 可以让这个更容易,且无需使用额外的锁。

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

这篇关于如何通过锁定方法的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆