我不知道为什么ReaderWriterLockSlim
以这种方式实施。我怀疑有充分的理由。
为什么不直接使用ConcurrentDictionary?然后您不必担心显式锁定。
也就是说,我看不出拥有多个可升级读卡器锁对您有什么帮助。考虑以下场景:
Thread1 enters the lock in upgradeable mode
Thread2 enters the lock in upgradeable mode
Thread1 searches for "xyzzy" and doesn't find it
Thread2 searches for "xyzzy" and doesn't find it
Thread2 upgrades to a write lock
Thread1 waits to upgrade to a write lock
Thread2 updates and releases the lock
Thread1 acquires the write lock and overwrites what Thread2 had written
为了防止 Thread1 覆盖 Thread2 所做的事情,您必须编写以下逻辑:
Enter upgradable read lock
if (!dict.TryGetValue(...))
{
Enter write lock
if (!dict.TryGetValue(...)) // extra check required!
{
}
}
当没有可升级的锁时,这正是您必须做的。