A usage scenario of ReaderWriterLock's UpgradeToWriterLock method, lockmode. upgrade
The advantage of ReaderWriterLock compared with mutex lock is that the Read and Write locks are separated from each other.
Of course, this article focuses not on ReaderWriterLock itself, but on its UpgradeToWriterLock method.
Consider the following scenarios.
There is a Dictionary. Multiple Threads modify and traverse it at the same time. When a thread traverses it (read lock), it needs to Remove the Dictionary based on certain conditions, which may be (less likely, otherwise it will be okay to directly use the read lock. This thread obtains the read lock. if you Remove the Dictionary directly, it will inevitably affect other threads that are also reading the lock. What should we do?
This is the time when the UpgradeToWriterLock method is available! The function of this method is to upgrade the current read lock to a write lock. After the upgrade, the thread will wait for the completion of other read locks, just like obtaining the write lock. Therefore, the next Remove operation is thread-safe. (Remember DowngradeFromWriterLock after the end)