Gary Fischbach
Gary Fischbach

Reputation: 41

An item with the same key has already been added to dictionary

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()  

I am using the below code:

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?

Thanks in advance for any assistance.

Upvotes: 4

Views: 5464

Answers (1)

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.

Upvotes: 2

Related Questions