我已经为此烦恼了一两个小时了。我需要一个线程安全的双向字典。根据我对字典的理解,它们在被阅读时是线程安全的,但是当被写到字典时就没有那么安全了。我试着编写了这个代码片段来理解正确,但是如果可能的话,复习将是很棒的。
class ConcurrentBidirectionalDictionary<TKey,UKey>
{
private Dictionary<TKey, UKey> BackingDictionary;
public ConcurrentBidirectionalDictionary()
{
BackingDictionary = new Dictionary<TKey, UKey>();
}
//Adding to dictionaries is not thread-safe ergo, lock when adding
private readonly object _SyncLock = new object();
public void Add(TKey item1, UKey item2)
{
if (!BackingDictionary.ContainsKey(item1) && !BackingDictionary.ContainsValue(item2))
{
lock (_SyncLock)
{
if (!BackingDictionary.ContainsKey(item1) && !BackingDictionary.ContainsValue(item2))
{
BackingDictionary.Add(item1, item2);
}
else
{
ThrowNewDuplicateKeyException(item1, item2);
}
}
}
else
{
ThrowNewDuplicateKeyException(item1, item2);
}
}
private void ThrowNewDuplicateKeyException(TKey item1, UKey item2)
{
if (BackingDictionary.ContainsKey(item1) && BackingDictionary.ContainsValue(item2))
{
throw new ArgumentException("Duplicate Keys not allowed", "item1, item 2", null);
}
else if (BackingDictionary.ContainsKey(item1))
{
throw new ArgumentException("Duplicate Keys not allowed", "item1", null);
}
else if (BackingDictionary.ContainsValue(item2))
{
throw new ArgumentException("Duplicate Keys not allowed", "item 2", null);
}
}
//Reading is thread safe, no lock needed
public TKey GetFromUKey(UKey UKey)
{
var Record = BackingDictionary.FirstOrDefault(x => EqualityComparer<UKey>.Default.Equals(x.Value, UKey));
if (Record.Equals(default(KeyValuePair<TKey,UKey>)))
{
throw new IndexOutOfRangeException($"Unable to find UKey {UKey}");
}
return Record.Key;
}
public UKey GetFromTKey(TKey TKey)
{
return BackingDictionary[TKey];
}
}发布于 2016-06-23 22:04:25
最好使用CouncurrentDictionary来减少锁争用锁争用:
class Map<X, Y>
{
public X this[Y y]
{
get { return YX[XY[YX[y]]]; } // Ensure Set completion
set { Set(value, y); }
}
public Y this[X x]
{
get { return XY[x]; }
set { Set(x, value); }
}
void Set(X x, Y y)
{
if (!YX.GetOrAdd(y, x).Equals(x))
throw new InvalidOperationException();
if (!XY.GetOrAdd(x, y).Equals(y))
throw new InvalidOperationException();
}
ConcurrentDictionary<X, Y> XY { get; } = new ConcurrentDictionary<X, Y>();
ConcurrentDictionary<Y, X> YX { get; } = new ConcurrentDictionary<Y, X>();
}发布于 2016-06-24 08:28:11
我想你对线程安全有一些误解。看看MSDN页面关于Dictionary。螺纹安全部分指出:
只要集合不被修改,字典就可以同时支持多个读者。即便如此,枚举一个集合本质上并不是一个线程安全的过程。在枚举与写访问争用的罕见情况下,必须在整个枚举期间锁定集合。若要允许多个线程访问集合以进行读写,您必须实现自己的同步。
这是因为当您编写字典时,它可以增加基础集合的大小,或者重新组织存储项目的内部“存储桶”。这些操作将移动可以以不可预知的方式中断并发读取操作的项。另一方面,如果在枚举过程中修改集合,则枚举将立即抛出。
底线是:您的GetFromTKey (read)和GetFromUKey (枚举)不是线程安全的。如果要同时读写,则必须将它们与Add方法同步。
https://codereview.stackexchange.com/questions/132900
复制相似问题