Only one thread can enter upgradeable mode at any given time
basically, you haven't done much better than just using a full lock - except lock
would actually have been faster.
Oddly enough, one good approach here is Hashtable
; especially since the value is object
, and the key is a reference-type (no extra boxing). Hashtable
is unusual in that reads are fully thread-safe; you only need to guard against multiple writers.
For example:
readonly Hashtable lookup = new Hashtable();
...
object val = lookup[key]; // no need to synchronize when reading
...
lock(lookup)
{
lookup[key] = newVal; // synchronize when writing
}