Due to performance problems, I have replaced ReaderWriterLock
with ReaderWriterLockSlim
. I am experiencing troubles, caused by code that functioned correctly when it was using a RWL.
As you can see, sometimes MethodA
(which acquires a write lock) calls another method (which acquires a read lock). The second method is also called from different places, so not always there is lock collision. Previously, AcquiringRead lock doesn't cause that problem.
Is there any solution except from placing "if IsRWheld"?
The problem is something like that:
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;
}
}
The call to MethodX from MethodA qualifies it as recursive use of the lock.
See the remarks on the MSDN page for 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 theLockRecursionPolicy.SupportsRecursion
flag to create instances of ReaderWriterLockSlim that allow recursion.
Another point to consider when replacing ReaderWriterLock
by ReaderWriterLockSlim
is that the latter implements IDisposable
.
This can make the replacement complex - as any types that own a ReaderWriterLockSlim
must also be IDisposable
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With