2

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?

4

3 回答 3

6
  1. 你的锁无效。您需要有一个实例来锁定。您目前每次都创建一个新的。
  2. 改用 aConcurrentDictionary<TKey, TValue>并使用AddOrUpdate. 这完全消除了对锁的需要:

    var value = port.getLabel() + ";" + cable + ";" + cableTemplate + "|";
    connections.AddOrUpdate(port.getParentName(), value, (k, v) => v + value);
    
于 2013-04-04T12:13:47.763 回答
2

在类的范围内移动你的同步对象:

public class Test
{    
    private object syncRoot = new object();

    private void Foo()
    {
        lock (this.syncRoot)
        {
            ....
        }
    }
}

是否将其设为静态,取决于您如何使用您的课程。

于 2013-04-04T12:14:45.963 回答
2

ConcurrentDictionary可以为您处理同步问题。

于 2013-04-04T12:15:36.333 回答