命名锁收藏在C#中? [英] Named Lock Collection in C#?
问题描述
我有多个线程写入数据到一个共同的来源,我想两个线程来阻止对方当且仅当他们接触相同的数据。
I have multiple threads writing data to a common source, and I would like two threads to block each other if and only if they are touching the same piece of data.
这将是不错的办法上的任意键锁定具体:
It would be nice to have a way to lock specifically on an arbitrary key:
string id = GetNextId();
AquireLock(id);
try
{
DoDangerousThing();
}
finally
{
ReleaseLock(id);
}
如果没有其他人试图锁定相同的密钥,我希望他们会能够同时运行。
If nobody else is trying to lock the same key, I would expect they would be able to run concurrently.
我可以互斥的简单的字典实现这一点,但我需要担心驱逐旧的,未使用的锁,并可能成为一个问题如果集增长过大。
I could achieve this with a simple dictionary of mutexes, but I would need to worry about evicting old, unused locks and that could become a problem if the set grows too large.
有没有这种类型的锁定模式的现有的实现。
Is there an existing implementation of this type of locking pattern.
推荐答案
您可以尝试使用 ConcurrentDictionary<字符串对象>
来创建一个名为对象实例。当你需要一把新锁实例(你以前没有使用过),可以将其添加到字典中(添加通过一个原子操作 GetOrAdd
),然后所有线程一旦你从字典,根据您的数据拉它可以共享相同的命名对象
You can try using a ConcurrentDictionary<string, object>
to create named object instances. When you need a new lock instance (that you haven't used before), you can add it to the dictionary (adding is an atomic operation through GetOrAdd
) and then all threads can share the same named object once you pull it from the dictionary, based on your data.
例如:
// Create a global lock map for your lock instances.
public static ConcurrentDictionary<string, object> GlobalLockMap =
new ConcurrentDictionary<string, object> ();
// ...
var oLockInstance = GlobalLockMap.GetOrAdd ( "lock name", x => new object () );
if (oLockInstance == null)
{
// handle error
}
lock (oLockInstance)
{
// do work
}
这篇关于命名锁收藏在C#中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!