Firstly, you should use the new ReaderWriterLockSlim
class, which is more efficient than the older one, and also avoids many cases of potential deadlock.
Secondly, it is not possible to avoid a writer having to wait for any thread that already has a read (or write) lock at the time that the writer wants to write - that's a fundamental part of the requirements of a reader/writer lock.
Thirdly, writers DO have precedence over readers when they are waiting for a write lock.
From the documentation for ReaderWriterLockSlim.EnterWriteLock()
:
If other threads have entered the lock in read mode, a thread that calls the EnterWriteLock method blocks until those threads have exited read mode.
When there are threads waiting to enter write mode, additional threads that try to enter read mode or upgradeable mode block until all the threads waiting to enter write mode have either timed out or entered write mode and then exited from it.
In this respect it seems to differ from ReaderWriterLock
- this looks like one of the things that has been fixed.
This is about the best you can get. The key thing is for the readers to keep their locks for the shortest time possible.
Also note that neither ReaderWriterLock
nor ReaderWriterLockSlim
support inter-process locks.