已将具有相同键的项目添加到字典中 [英] An item with the same key has already been added to dictionary

查看:32
本文介绍了已将具有相同键的项目添加到字典中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

运行以下代码时,有时会出现以下错误:

When running the below code I sometimes get the following error:

 System.ArgumentException: An item with the same key has already been added.
   at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
   at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
   at Interfaces.InterfaceBase.GetSettings()  

我正在使用以下代码:

For Each dr As DataRow In dsData.Tables("tblData").Rows  
    If InterfaceSettings.ContainsKey(dr("SettingsName").ToString.Trim) = False Then  
        InterfaceSettings.Add(dr("SettingsName").ToString.Trim, dr("SettingsValue").ToString.Trim)  
    End If  
Next

我在数据库表中没有重复项.知道为什么这会失败吗?

I have no duplicates in the database table. Any idea why this would ever fail?

在此先感谢您的帮助.

推荐答案

当代码在尝试添加键之前检查键时,如何发生重复键异常?

How does a duplicate key exception occur when code is checking for the key before attempting to add it?

我认为答案是代码是共享的.当一个线程检查条件并即将更新字典但被另一个线程中断时会发生错误,该线程然后更新字典,然后原始线程执行相同的操作,导致重复键异常.

I think the answer is that the code is shared. The error occurs when a thread checks the condition and is about to update the dictionary but is interrupted by another thread which then updates the dictionary and then the original thread does the same resulting in a duplicate key exception.

这篇关于已将具有相同键的项目添加到字典中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆