c# – 用ReaderWriterLockSLim替换ReaderWriterLock – 麻烦

前端之家收集整理的这篇文章主要介绍了c# – 用ReaderWriterLockSLim替换ReaderWriterLock – 麻烦前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
由于性能问题,我已经用 ReaderWriterLockSlim替换了 ReaderWriterLock.我遇到了麻烦,这是由使用RWL时正常运行的代码引起的.

如您所见,有时MethodA(获取写锁定)调用另一个方法(获取读锁定).第二种方法也是从不同的地方调用的,因此并不总是存在锁定冲突.以前,AcquiringRead锁定不会导致该问题.

除了放置“if IsRWheld”之外,有什么解决方案吗?

问题是这样的:

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的评论

By default,new instances of
ReaderWriterLockSlim are created with
the LockRecursionPolicy.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.

原文链接:https://www.f2er.com/csharp/100947.html

猜你在找的C#相关文章