Vb.net 已将具有相同键的项添加到字典中

Vb.net 已将具有相同键的项添加到字典中,vb.net,Vb.net,运行以下代码时,有时会出现以下错误: 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, B

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

 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
我在数据库表中没有重复项。你知道为什么这会失败吗


提前感谢您的帮助。

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


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

您是否确认dr(“SettingsName”)中没有重复项,并且它们都不是null或String.Empty?如果您有一个或两个项目是空的,它将添加一个副本。不幸的是,您发布的异常与代码无关。如果查看堆栈跟踪,您将看到异常是通过调用Dictionary.Insert而不是Dictionary.Add生成的。我将搜索该过程的其余部分以查看调用Dictionary Insert的位置。@Competite_tech-
.Add
调用
.Insert
内部:
公共void Add(TKey,TValue值){Insert(key,value,true);}
--Insert是内部私有method@J...:我理解这一点,但除非编译器优化生成的代码以删除要添加的引用(我不认为是这样),否则堆栈跟踪将始终包括对添加的调用:at System.Collections.Generic.Dictionary
2.Insert(TKey-key,TValue-value,Boolean-add)在System.Collections.Generic.Dictionary
2.add(TKey-key,TValue-value)@competable\u-tech-否,如果异常是通过调用另一个类中的方法引发的,则不会。在这种情况下,他的代码调用了
.GetSettings()
,其中包含添加到词典中的代码。无法在用户代码中调用
。插入
-这是TDictionary中的私有方法,无法访问。