由于性能问题,我已经用
ReaderWriterLockSlim
替换了
ReaderWriterLock
.我遇到了麻烦,这是由使用RWL时正常运行的代码引起的.
如您所见,有时MethodA(获取写锁定)调用另一个方法(获取读锁定).第二种方法也是从不同的地方调用的,因此并不总是存在锁定冲突.以前,AcquiringRead锁定不会导致该问题.@H_403_3@
除了放置“if IsRWheld”之外,有什么解决方案吗?@H_403_3@
问题是这样的:@H_403_3@
class Avacado { ReaderWriterLockSlim _lock = new ReaderWriterLockSlim(); void MethodA() { _lock.TryEnterWriteLock(-1); LockedList.Add(someItem) var result = MethodX(); _lock.ExitWriteLock(); } object MethodX() { //if called from MethodA,it will throw an exception _lock.TryEnterReadLock(-1); //...some stuff with LockedList... var result = LockList.Something(); _lock.ExitReadLock(); return result; } }
解决方法
从MethodA调用MethodX将其限定为锁的递归使用.
请参阅 MSDN page上针对ReaderWriterLockSlim的评论:
请参阅 MSDN page上针对ReaderWriterLockSlim的评论:
By default,new instances of
ReaderWriterLockSlim are created with
theLockRecursionPolicy.NoRecursion
flag and do not allow recursion. This
default policy is recommended for all
new development,because recursion
introduces unnecessary complications
and makes your code more prone to
deadlocks. To simplify migration from
existing projects that use Monitor or
ReaderWriterLock,you can use the
LockRecursionPolicy.SupportsRecursion
flag to create instances of ReaderWriterLockSlim that allow recursion.@H_403_3@