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.
Using a ConcurrentDictionary
was the answer, thankfully inspired by user454076.