根据参数锁定 [英] Locking based on parameters

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

问题描述

假设我有这种方法:

void Foo(int bar)
{
    // do stuff
}

这是我想要的行为 Foo 具有:

Here is the behavior I want Foo to have:


  1. 如果线程1 调用 Foo(1)线程2 调用 Foo(2),两个线程可以同时运行。

  1. If thread 1 calls Foo(1) and thread 2 calls Foo(2), both threads can run concurrently.

如果线程1 调用 Foo(1)线程2 调用 Foo(1),两个线程不能并发运行。

If thread 1 calls Foo(1) and thread 2 calls Foo(1), both threads cannot run concurrently.

.net 中是否有一种很好的标准方法来指定这种行为?我有一个使用对象字典进行锁定的解决方案,但感觉有点混乱。

Is there a good, standard way in .net to specify this type of behavior? I have a solution that uses a dictionary of objects to lock on, but that feels kind of messy.

推荐答案

使用可以为不同的参数提供不同的锁定对象。实例化基础对象时(或静态,如果适用),设置字典:

Use a dictionary that provides different lock objects for the different arguments. Set up the dictionary when you instantiate the underlying object (or statically, if applicable):

var locks = new Dictionary<int, object>() {
    {1, new Object()},
    {2, new Object()},
    …
};

然后在您的方法中使用它:

And then use it inside your method:

void Foo(int bar) {
    lock (locks[bar]) {
        …
    }
}

我不会说这个解决方案很麻烦,相反:提供良好的锁定粒度是值得称赞的,因为锁定值类型在.NET中不起作用,具有映射是显而易见的解决方案。

I wouldn’t say that this solution is messy, on the contrary: providing a fine lock granularity is commendable and since locks on value types don’t work in .NET, having a mapping is the obvious solution.

但是请注意:以上内容仅在字典不是同时存在的情况下才有效修改并阅读。因此,最好在设置字典后将其视为只读。

Be careful though: the above only works as long as the dictionary isn’t concurrently modified and read. It is therefore best to treat the dictionary as read-only after its set-up.

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

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