Reputation: 373
I'm working on a C# website and I just started getting some random errors over the previous weekend. The error is being generated from random pages on the site, and of course, there is hardly any information to go on. Here's the 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 System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value)
at System.Collections.ObjectModel.KeyedCollection`2.AddKey(TKey key, TItem item)
at System.Collections.ObjectModel.KeyedCollection`2.InsertItem(Int32 index, TItem item)
at System.Collections.ObjectModel.Collection`1.Add(T item)
at CommerceBuilder.Catalog.DefaultUrlRewriter.InitializeCache()
at CommerceBuilder.Catalog.DefaultUrlRewriter.a(String A_0)
at CommerceBuilder.Catalog.DefaultUrlRewriter.RewriteUrl(String sourceUrl)
at CommerceBuilder.Services.b.c(Object A_0, EventArgs A_1)
at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
I've read a bunch of articles on similar errors, but I haven't added any new dictionary items that I know of, so I'm not sure where to start. Can anyone please give me some suggestions?
Upvotes: 0
Views: 1887
Reputation: 52290
This sort of thing can happen when two threads are simultaneously attempting to add an entry to a dictionary that is not thread safe.
If you have the ability to modify the code that is raising the error, I would suggest using a System.Collections.Concurrent.ConcurrentDictionary instead of a System.Collections.Dictionary.
Upvotes: 2