"字典中已添加了具有相同键的项目"

zzi*_*rna 1 c# synchronization dictionary

我试图在C#中为字典添加一些元素,但我遇到了一些问题.我是C#开发的新手,所以我希望有人可以帮助我.

添加元素的代码是:

if (!connections.ContainsKey(port.getParentName()))
{
    connections.Add(port.getParentName(), port.getLabel() + ";" + cable + ";" + cableTemplate + "|");
}
else
{
    connections[port.getParentName()] += port.getLabel() + ";" + cable + ";" + cableTemplate + "|";
}
Run Code Online (Sandbox Code Playgroud)

虽然我正在检查密钥是否已经包含在我的端口字典中,但我得到了:

“An item with the same key has already been added”
Run Code Online (Sandbox Code Playgroud)

还要提到我是异步获取数据所以我猜这是一个同步问题.我试图通过锁定这段代码来解决这个问题,但这似乎并没有解决问题:

System.Object lockThis = new System.Object();
lock (lockThis)
{
    ....
}
Run Code Online (Sandbox Code Playgroud)

还要提一下,我并没有一直得到这个错误.只是偶尔启动应用程序时.知道是什么原因引起的吗?我的同步方式是错误的还是别的?

Dan*_*rth 5

  1. 你的锁无效.您需要有一个实例才能锁定.您目前每次都会创建一个新的.
  2. 使用ConcurrentDictionary<TKey, TValue>替代和使用AddOrUpdate.这样就完全不需要锁定了:

    var value = port.getLabel() + ";" + cable + ";" + cableTemplate + "|";
    connections.AddOrUpdate(port.getParentName(), value, (k, v) => v + value);
    
    Run Code Online (Sandbox Code Playgroud)