user3805884
user3805884

Reputation: 133

Update key in ConcurrentDictionary

I want to add an UpdateKey method to an observable wrapper class around a ConcurrentDictionary. Something like this:

private bool UpdateKeyWithNotification(TKey key1, TKey key2)
{
    if (key1.Equals(key2)) return false;
    TValue value;
    var result = _dictionary.TryRemove(key1, out value);
    if (!result) return false;
    result = _dictionary.TryAdd(key2, value);
    if (result) NotifyObserversOfChange();
    return result;
}

Obviously this operation is no longer atomic as it does a remove and then add. I don't have much of a performance requirement on UpdateKeyWithNotification as it will be used seldom but I'd like to have some type of execution guarantee for the backing _dictionary between TryRemove and TryAdd. I could add some type of RWMutex or a lock object around the TryRemove and TryAdd operations. But that'd probably mean I'd also have to add lock statements around all other methods in the class. Is there an alternative to my solution?

Upvotes: 0

Views: 686

Answers (1)

Kit
Kit

Reputation: 21759

You simply cannot use ConcurrentDictionary to do this atomically with any of its built in methods (and note that the SyncRoot property won't help as it's not supported.

You can use an external synchronization mechanism, but then you're immediately not gaining anything from ConcurrentDictionary, in fact making it less concurrent.

Since you're essentially re-keying some data, I would suggest that you derive a thread-safe wrapper from DictionaryBase and add your specialize method.

Upvotes: 1

Related Questions