日期:2014-05-17  浏览次数:21126 次

求解C#字典ConcurrentDictionary.ContainsKey(key)为true之后,ConcurrentDictionary[key]报不存在
求解C#字典dc.ContainsKey(key)为true之后,dc[key]报不存在key异常
字典结构如下:

//以下代码是在主线程中
//TryAdd全部是添加成功的
ConcurrentDictionary<string, ConcurrentDictionary<ECommandPriority, ConcurrentDictionary<string, CommandFlag>>> dcCommandList;

//ECommandPriority是一个枚举。

this.dcCommandList = new ConcurrentDictionary<string, ConcurrentDictionary<ECommandPriority, ConcurrentDictionary<string, CommandFlag>>>();

if (this.dcCommandList.TryAdd(terminalPhone, new ConcurrentDictionary<ECommandPriority, ConcurrentDictionary<string, CommandFlag>>()))
{
if (!this.dcCommandList[terminalPhone].TryAdd(ECommandPriority.Highest, new ConcurrentDictionary<string, CommandFlag>()))
{
}
if (!this.dcCommandList[terminalPhone].TryAdd(ECommandPriority.Normal, new ConcurrentDictionary<string, CommandFlag>()))
{
}
if (!this.dcCommandList[terminalPhone].TryAdd(ECommandPriority.Lowest, new ConcurrentDictionary<string, CommandFlag>()))
{
}
}
else
{
}


下面是使用时报错代码,是在另一个线程中,在报异常时通过监视变量,发现this.dcCommandList.ElementAt(i).Value[ECommandPriority.Highest]是存在的

------解决方案--------------------
分两步做,就不是原子操作,就会出现同步问题。
你应该用:
ConcurrentDictionary.TryGet