I've recently bumped into multithreading perfomance issue, and started to investigate how to optimize current code.
The most suitable solution for my issue is using readerwriter lock, but this article of Jeffrey Richter made me have some doubt in using this kind of locks. I have much more readers then writers, but writer changes should be applied as fast as possible.
Does this behavior still remain in .net 4.5 version of readerwriter lock? I mean priority of reader threads over writer threads?
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()
: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
norReaderWriterLockSlim
support inter-process locks.