I am trying to add some elements to a dictionary in C# but I've been running into some problems. I am new to C# development so I hope someone could help me with this.
The code for adding the element is:
if (!connections.ContainsKey(port.getParentName()))
{
connections.Add(port.getParentName(), port.getLabel() + ";" + cable + ";" + cableTemplate + "|");
}
else
{
connections[port.getParentName()] += port.getLabel() + ";" + cable + ";" + cableTemplate + "|";
}
Although I'm checking if the key is allready contained in my ports dictionary I'm getting:
“An item with the same key has already been added”
Have to mention also that I am getting the data asynchronously so I would guess that this is a synchronization issue. I tried to handle this by locking this block of code but this does not seem to solve the problem:
System.Object lockThis = new System.Object();
lock (lockThis)
{
....
}
Also have to mention that I am not getting this error all the time. Just that occasionally when starting the application. Any idea what could be causing this? Is the way I'm making the synchronization wrong or is it something else?