I am trying to use ReaderWriterLockSlim to lock some database work in an async method like this:
readerWriterLock.EnterWriteLock();
using (var db = new MyContextDB())
{
// look something up and alter it
}
readerWriterLock.ExitWriteLock();
This throws an exception as multiple threads try to enter writelock at the same time. Right now I could use a lock object but I thought I would use the ReaderWriterLockSlim so I could try some optimisation with read/write & upgradeable.
The MSDN samples of ReaderWriterLockSlim are a little confusing for me. Is there a simple way to just have the thread wait for the lock to become available? IsWriteLockHeld property says it just tests if the current thread is locked. WaitingWriteCount says it gives the number of threads waiting to enter but how do you make a thread wait to enter? I could not find that in any samples. Am I meant to just loop until it does not throw an exception? That does not seem right.