如何锁定具有相同ID的对象? [英] How to lock objects withthe same ids?
问题描述
我有以下代码:
public void Update(Foo foo)
{
lock(_locker)
{
UpdateFirstPart(foo.First);
UpdateSecondPart(foo.Second);
UpdateThirdPart(foo.Third);
}
}
public class Foo
{
public int Id;
public Some1 First;
public Some2 Second;
public Some3 Third;
}
方法更新
可以在两个或多个线程中执行,我使用 lock
来防止 foo
出现货币问题。但是我只想锁定具有 Id
相似的 Foo
。例如,如果一个线程使用Foo.Id = 1执行方法 Update
,而另一个线程使用Foo.Id =执行 Update
2然后不需要 lock
,并且如果两个线程使用两个实例 Foo
和相同的 Id
,锁
是必需的。是否可以创建这样的锁?
Method Update
can be performed in two or more threads and I use lock
to prevent cuncurency problems with foo
. But I would like to lock only those Foo
that have similar Id
. For instance if one thread executes method Update
with Foo.Id = 1 and another thread executes Update
with Foo.Id = 2 then lock
is not needed and if two threads execute Update with two instances Foo
with the same Id
, lock
is needed. Is it possible to create a such lock?
推荐答案
您可以使用此类为每个ID获取一个锁定对象:
You could use this class to get a lock object for every Id:
public class MultiLockObjects<TKey>
{
private readonly ConcurrentDictionary<TKey, Object> _multiLocker = new ConcurrentDictionary<TKey, Object>();
public Object this[TKey key]
{
get
{
Object lockObj = _multiLocker.GetOrAdd(key, tKey => new Object());
return lockObj;
}
}
}
然后持有它的一个实例
private MultiLockObjects<int> _idLocks = new MultiLockObjects<int>();
用法很简单:
public void Update(Foo foo)
{
Object idLockObject = _idLocks[foo.Id];
lock (idLockObject)
{
UpdateFirstPart(foo.First);
UpdateSecondPart(foo.Second);
UpdateThirdPart(foo.Third);
}
}
这篇关于如何锁定具有相同ID的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!