是否有必要使用
Consider this scenario: I have a dictionary
. Things can be added to it. But things can t be removed from it. When things are added, it can be a very expensive operation in terms of time (only hundreds of milliseconds, but still costly relative to the rest of the app) If I wanted to add something and it wasn t already there, would there be anything to gain by:
- first acquiring a read lock, then checking for existence,
- then entering an upgradable read lock, and checking again,
- then entering a write lock if the item is still not present in the dictionary?
类似于:
void populateIfNotPresent( object thing )
{
_lock.EnterReadLock( ) ;
bool there = _dictionary.ContainsKey(thing);
_lock.ExitReadLock( ) ;
// Remember, the specs say nothing can be removed from this dictionary.
if (!there)
{
_lock.EnterUpgradeableReadLock( ) ;
try
{
if( !_dictionary.ContainsKey( thing ) )
{
_lock.EnterWriteLock( ) ;
try
{
populate( thing ) ;
}
finally
{
_lock.ExitWriteLock( ) ;
}
}
}
finally
{
_lock.ExitUpgradeableReadLock( ) ;
}
}
}
当时,只有一只读物可以进入一个可升级的24小时,但不会阻止任何其他的read子进入一个读24小时,因此,似乎在双重检查锁上有价值。
你认为什么? 难道这种高技能吗?