The following code does not complete, because second reader (tRead2) cannot acquire lock.
ReaderWriterLockSlim rw = new ReaderWriterLockSlim();
var tRead1 = Task.Run
(
() => rw.EnterReadLock()
);
var tWrite = Task.Run
(
() =>
{
Thread.Sleep(1000);
rw.EnterWriteLock();
}
);
var tRead2 = Task.Run
(
() =>
{
Thread.Sleep(3000);
rw.EnterReadLock();
}
);
Task.WaitAll(tRead1, tRead2);
I didn't expect this situation, I thought that since writer (tWrite) cannot get the lock, then the tRead2 would be allowed to do that (and tWrite will wait till all read-mode locks are released). I interpret this unexpected behavior as a way to disallow starvation of writer.
Is there any synchronization structure that would allow tRead2 to get the lock (even if tWrite might be starved)?