简体   繁体   中英

C# Dictionary ContainsKey/TryGetValue not working

I've looked around for a while and seen plenty of references to modifying GetHashCode() and things when playing with ContainsKey() and TryGetValue() - but all those issues and examples have all been with some obscure user-specific key.

I have a basic Dictionary<long, object> . When trying either ContainsKey() or TryGetValue() , it doesn't always get a hit (when it should) and moves on to attempting to populate the missing entry (as it technically should if that were the case).

You guessed it: it then complains about the existing key because, well, it exists.

So why is it having problems matching a basic long key and how do you make it behave?

Edit: Code. I have tried several things. In their most basic form:

public void Add(long id)
    {
        if (AreaDataDict.ContainsKey(id)) return;

        AreaData ad = new AreaData(id);
        ad.Load();
        AreaDataDict.Add(id, ad);
    }

Also:

public void Add(long id)
{
    AreaData areaData;
    if (AreaDataDict.TryGetValue(id, out areaData)) return;

    AreaData ad = new AreaData(id);
    ad.Load();
    AreaDataDict.Add(id, ad);
}

Edit 2: No key changes are happening. Other than adding if the value is not found, data is only read from this.

使用ConcurrentDictionary是答案,幸好受到用户454076的启发。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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