gpt4 book ai didi

c# - ReaderWriterLockSlim 出错

转载 作者:太空狗 更新时间:2023-10-29 19:39:40 25 4
gpt4 key购买 nike

我遇到了这个异常
正在释放读锁而不被持有。
在 System.Threading.ReaderWriterLockSlim.ExitReadLock() 在 .. GetBreed(字符串)

下面是代码中唯一访问锁的地方。如您所见,没有递归。我无法理解这种异常是如何发生的。

static readonly Dictionary<string, BreedOfDog> Breeds 
= new Dictionary<string,BreedOfDog>();

static BreedOfDog GetBreed(string name)
{
try
{
rwLock.EnterReadLock();
BreedOfDog bd;
if (Breeds.TryGetValue(name, out bd))
{
return bd;
}
}
finally
{
rwLock.ExitReadLock();
}

try
{
rwLock.EnterWriteLock();
BreedOfDog bd;
//make sure it hasn't been added in the interim
if (Breeds.TryGetValue(t, out bd)
{
return bd;
}
bd = new BreedOfDog(name); //expensive to fetch all the data needed to run the constructor, hence the caching

Breeds[name] = bd;
return bd;
}
finally
{
rwLock.ExitWriteLock();
}
}

最佳答案

我猜你有一些可重入的东西,它在获取锁时抛出异常。无论你是“拿锁”、“尝试”还是“尝试”、“拿锁”,都有一个 catch-22,但是“拿锁”、“尝试”的失败案例更少(“在 take 和尝试”的可能性微乎其微,您无需强调)。

将“获取锁”移到“try”之外,看看实际异常是什么。

问题很可能是您未能取得锁(可能是重入),然后试图解锁您没有取得的东西。这可能意味着在获取锁的原始代码中出现异常,因为在只获取一次时尝试释放两次。

注意:Monitor 有带有“ref bool”参数的新重载来帮助处理这种情况——但不是其他锁类型。

关于c# - ReaderWriterLockSlim 出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10303191/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com