简体   繁体   English

在Dictionary ContainsKey检查中找不到ArgumentException

[英]ArgumentException not found in Dictionary ContainsKey check

I have code like this: 我有这样的代码:

if (!likeDict.ContainsKey(s))
{
    likeDict.Add(s, s);
}

And I keep getting an error that an item with the same key has already been added. 而且我不断收到一个错误消息,即已添加具有相同密钥的项目。 I thought ContainsKey is the check for this and that is where the error is occuriing, not at the add line. 我以为ContainsKey是对此的检查,这就是发生错误的地方,而不是添加行。 Am I misinterpreting ContainsKey? 我误解了ContainsKey吗?

It sounds like you are using the dictionary in a multithreaded scenario. 听起来您好像在多线程方案中使用字典。 If this is the case, you can switch to using ConcurrentDictionary<TKey, TValue> which provides the following TryAdd method: 在这种情况下,可以切换到使用ConcurrentDictionary<TKey, TValue> ,它提供以下TryAdd方法:

bool added = likeDict.TryAdd(s, s);

If you are using this dictionary as a cache for equivalent objects, you could also use the GetOrAdd method: 如果您将此字典用作等效对象的缓存,则还可以使用GetOrAdd方法:

var value = likeDict.GetOrAdd(s, s);
bool added = object.ReferenceEquals(value, s);

The error could happen if this is static/shared resource (as pointed in previous comments). 如果这是静态/共享资源(如先前注释中所述),则可能会发生错误。 In this case, apply lock statement. 在这种情况下,请应用lock语句。

Hope this will help. 希望这会有所帮助。 My best, AB 我最好的AB

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM