Downgrading ReaderWriterLockSlim UpgradeableReadLock to simple ReadLock
-
The documentation of
ReaderWriterLockSlim.EnterUpgradeableReadLock
says: "A thread in upgradeable mode can downgrade to read mode or upgrade to write mode." How do I downgrade the lock to a read lock? The documentation does't tell... -
The documentation of
ReaderWriterLockSlim.EnterUpgradeableReadLock
says: "A thread in upgradeable mode can downgrade to read mode or upgrade to write mode." How do I downgrade the lock to a read lock? The documentation does't tell...To upgrade to write mode call
EnterWriteLock
and to downgrade, callExitWriteLock
Navaneeth How to use google | Ask smart questions
-
To upgrade to write mode call
EnterWriteLock
and to downgrade, callExitWriteLock
Navaneeth How to use google | Ask smart questions
Thanks, but I meant to downgrade from UpgradeableReadLock to simple ReadLock. I don't need WriteLock. The rationale is that since only one thread can acquire UpgradeableReadMode, I want to downgrade it when I know it's not needed so that another thread can acquire it.
-
Thanks, but I meant to downgrade from UpgradeableReadLock to simple ReadLock. I don't need WriteLock. The rationale is that since only one thread can acquire UpgradeableReadMode, I want to downgrade it when I know it's not needed so that another thread can acquire it.
Well, the below code will answer it
class Program
{
static ReaderWriterLockSlim rwSlim = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
static void Main(string[] args) {
// entering upgradable read lock
rwSlim.EnterUpgradeableReadLock();
Console.WriteLine(rwSlim.IsUpgradeableReadLockHeld);// downgrading to readlock. Now you are in read lock rwSlim.EnterReadLock(); Console.WriteLine(rwSlim.IsReadLockHeld); // exiting from upgradable lock rwSlim.ExitUpgradeableReadLock(); Console.WriteLine(rwSlim.IsUpgradeableReadLockHeld); // exiting read lock rwSlim.ExitReadLock(); Console.WriteLine(rwSlim.IsReadLockHeld); }
}
You need to supply
LockRecursionPolicy.SupportsRecursion
to indicate that you need recursive locks.Navaneeth How to use google | Ask smart questions