dan*_*dan 8 c# multithreading readerwriterlockslim
我得到了这个异常
读取锁定被释放而没有被释放.
在System.Threading.ReaderWriterLockSlim.ExitReadLock()at .. GetBreed(String)
下面是访问锁的代码中唯一的位置.如您所见,没有递归.我无法理解如何发生此异常.
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();
}
}
Run Code Online (Sandbox Code Playgroud)
我猜你有一些可重入的东西,并且在获取锁时抛出异常。无论你“拿锁”、“尝试”还是“尝试”、“拿锁”,都有一个第 22 条军规,但“拿锁”、“尝试”的失败案例较少(“在拿锁和尝试之间中止”)尝试”的可能性微乎其微,你不需要强调)。
将“take the lock”移到“try”之外,看看实际的异常是什么。
问题很可能是您未能获取锁定(可能是重入),然后尝试解锁您没有获取的内容。这可能意味着在获取锁的原始代码中会出现异常,因为在只获取一次锁时尝试释放两次。
注意:监视器具有带有“ref bool”参数的新重载,以帮助解决此情况 - 但不适用于其他锁定类型。