【发布时间】:2018-12-18 18:30:24
【问题描述】:
我想在 ConcurrentDictionary 周围的可观察包装类中添加一个 UpdateKey 方法。像这样的:
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;
}
显然此操作不再是原子操作,因为它先删除然后添加。我对 UpdateKeyWithNotification 没有太多的性能要求,因为它很少使用,但我希望在 TryRemove 和 TryAdd 之间为支持 _dictionary 提供某种类型的执行保证。我可以在 TryRemove 和 TryAdd 操作周围添加某种类型的 RWMutex 或锁定对象。但这可能意味着我还必须在类中的所有其他方法周围添加锁定语句。我的解决方案有替代方案吗?
【问题讨论】:
标签: c# dictionary concurrency