【问题标题】:An item with the same key has already been added to dictionary具有相同键的项目已添加到字典中
【发布时间】:2013-07-11 17:34:32
【问题描述】:

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

 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。
  • @competent_tech - .Add 在内部调用 .Insertpublic void Add(TKey key, TValue value) { Insert(key, value, true); } --- Insert 是内部私有方法
  • @J...:我理解,但除非编译器优化生成的代码以删除对 Add 的引用,我不相信这种情况,堆栈跟踪将始终包含调用先添加:在 System.Collections.Generic.Dictionary2.Insert(TKey key, TValue value, Boolean add) at System.Collections.Generic.Dictionary2.Add(TKey key, TValue value)
  • @competent_tech - 不,如果异常是通过调用另一个类中的方法引发的,则不会。在这种情况下,他的代码调用了.GetSettings(),其中包含添加到字典中的代码。无法在用户代码中调用 .Insert - 它是 TDictionary 中的私有方法,无法访问。

标签: vb.net


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2013-02-16
    • 2013-01-14
    • 2013-03-18
    • 2023-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多