首页 新闻 会员 周边

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

0
悬赏园豆:10 [已解决问题] 解决于 2013-12-13 10:50

求解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]是存在的

Selway的主页 Selway | 初学一级 | 园豆:-6
提问于:2013-12-13 08:25
< >
分享
最佳答案
1

如果使用 TryAdd 的话,请使用 TryGet 读取。

这不是 ConcurrentDictionary 的 BUG,是你的代码逻辑有问题。

收获园豆:10
Launcher | 高人七级 |园豆:45045 | 2013-12-13 09:31

我换成TryGet确实没事了,但是为什么TryAdd是成功的,用dc[key]会出错呢

Selway | 园豆:-6 (初学一级) | 2013-12-13 09:48

@Selway: 因为它不是线程安全方法。使用 ConcurrentDictionary 时,应该使用它提供的线程安全的方法,TryXXX 形式的方法。

Launcher | 园豆:45045 (高人七级) | 2013-12-13 09:59
其他回答(2)
0

这本身就是不合理的?是不是其他地方的问题,报到这了,还有是不是还有其他地方操作这个字典?

幕三少 | 园豆:1384 (小虾三级) | 2013-12-13 08:28

没有了,只有这两个地方,上面的只会添加,下的是使用、修改和删除

支持(0) 反对(0) Selway | 园豆:-6 (初学一级) | 2013-12-13 08:35
0

多个地方都操作了吧,导致在线程中数据不同步.最好在读写DIc的地方Lock下

平常心队长 | 园豆:1113 (小虾三级) | 2013-12-13 08:57
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册