DefenestrationDay DefenestrationDay - 23 days ago 11
C# Question

Dictionary Add() exception on locked Dictionary

My code is throwing an Argument Exception, complaining about "An item with the same key has already been added."

I am locking on the object that complains, so I don't know how it is possible for it to be updated on another thread.

The WaypointIconDictionary is static.

Here is the code

try
{
lock (WaypointIconDictionary)
{
if (!WaypointIconDictionary.ContainsKey(waypoint.TypeOfWaypoint))
{
var thisIcon = waypoint.Icon;
var index = IconCache.LoadIcon(thisIcon, thisIcon.Width / 2, thisIcon.Height);
WaypointIconDictionary.Add(waypoint.TypeOfWaypoint, index);
}
IconCache.DrawIcon(graphics, x, y, WaypointIconDictionary[waypoint.TypeOfWaypoint], false);
}
}
catch (Exception ex)
{
Logger.Error("Waypoint drawing {0}", ex.Message);
}

Answer

This might not be a locking issue at all: it might be that you are actually trying to add the same key twice.

If you are absolutely sure that this is the only place where new entries are added to the dictionary, this exception could only be caused by:

  1. waypoint being overwritten by another thread
  2. IconCache.LoadIcon having a nasty side-effect that causes this thread to call this method again.

Step through the code or log what you are adding so you know what is going on.

Comments