我有一个具有许多线程的应用程序,其中每个线程都对GUID引用的资源执行某些操作,其中所说的GUID作为字符串存储在列表中。任何时候,GUID引用的资源都只能进行一项操作。
我试图为此和一个简单的列表使用锁语句。我遇到的问题是,我似乎无法安全地进行检查,以查看列表是否在lock语句内包含GUID,然后在其后跟随另一个lock语句将其添加到列表中。似乎有多个线程时,每个线程都检查以查看该GUID是否在列表中,并且检查均返回false,因此它们都添加了GUID(明显的问题)。
另外,我不能将检查与将GUID添加到字符串列表的语句放在同一锁内,因为如果这样做,该锁将被保留,从而防止正在使用该资源的其他线程将其从内存中删除。列表(他们无法获取锁)。
我希望您能原谅我的原始示例,但是我不知道如何在多线程环境中可靠地测试和锁定。不幸的是,我也不愿意为客户更改应用程序的设计。
如果您要推荐一个类(class)/图书馆,不妨举一个小例子。
private static readonly object _guidLock = new object();
private static List<string> guidList = new List<string>();
public static bool isGuidLocked(string guid)
{
lock (_guidLock)
{
if (guidList.Contains(guid)) return true;
return false;
}
}
public static bool lockGuid(string guid)
{
while (isGuidLocked(guid)) { }
lock (_guidLock)
{
guidList.Add(guid);
}
return true;
}
public static bool releaseGuid(string guid)
{
lock (_guidLock)
{
guidList.Remove(guid);
}
return true;
}
public static void doWorkOnGuid(string guid)
{
lockGuid(guid);
// do something there
releaseGuid(guid);
}
最佳答案
不要使用列表。 .NET提供了线程安全的集合。
在这种情况下,您可能需要使用GUID作为键的ConcurrentDictionary。
请参见 namespace :System.Collections.Concurrent
The System.Collections.Concurrent namespace provides several thread-safe collection classes that should be used in place of the corresponding types in the System.Collections and System.Collections.Generic namespaces whenever multiple threads are accessing the collection concurrently.
关于c# - 多线程,锁定和字符串值列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34584791/