-1

I am trying to use a ReaderWriterLock for a shared resource between two Tasks.For some reason it starts waiting indefinitely:

class State {

        private const int TIMEOUT = 5000;
        private ReaderWriterLock lck = new ReaderWriterLock();
        private TimeSpan lastIssuedAt;

        public TimeSpan LastIssuedAt {
            get {

                this.lck.AcquireReaderLock(TIMEOUT);
                return this.lastIssuedAt;
            }
            set {
                this.lck.AcquireWriterLock(TIMEOUT);
                this.lastIssuedAt = value;
            }
        }
}

When a task tries to get the property LastIssuedAt it just blocks and I do not understand why.

SUNIL DHAPPADHULE
  • 2,755
  • 17
  • 32
Bercovici Adrian
  • 8,794
  • 17
  • 73
  • 152

1 Answers1

1

Take a look at the example on MSDN: https://learn.microsoft.com/en-us/dotnet/api/system.threading.readerwriterlock?view=netframework-4.8

You forgot to release the lock. A common pattern for doing so is try/finally:

ReaderWriterLock lck = new ReaderWriterLock();

lck.AcquireReaderLock(timeOut);
try
{
    // Do what needs to be done under the lock
}
finally 
{
    // Ensure that the lock is released.
    lck.ReleaseReaderLock();
}

Also, check out ReaderWriterLockSlim: https://learn.microsoft.com/en-us/dotnet/api/system.threading.readerwriterlockslim?view=netframework-4.8 Which MSDN recommends for new development.

Peter Sulucz
  • 116
  • 4