At the moment I have a very strange issue regarding locking a dictionary. I have two different threads that access the dictionary, one thread puts in some entries, the other tries to read them out. All is well while making the entries, the strangest of problems occurs when I try to extract some values from the dictionary.
Here is what it looks like
lock (myDictionary)
{
//Add an entry here for a key.
}
// Retreival
lock(myDictionary)
{
if (myDictionary.ContainsKey(key))
myDictionary.TryGetValue(key, out store);
}
As soon as a thread enters the above code, the keys are not found. BUT if I write the following
lock(myDictionary)
{
Console.WriteLine(myDicionary.Count)
if (myDictionary.ContainsKey(key))
myDictionary.TryGetValue(key, out store);
}
Out of nowhere I see the same dictionary containing the keys that were not found in the prior code. Now you guys can argue that what happened was the I/O delay caused enough time for the dictionary to store some values, but I donot have any timeouts or something that causes me to loose any processing, what this means till the dictionary contains some values to be extracted, next processing step will not occur and my program will wait till it gets some values. But unfortunately, this does not happen unless I put a Console.WriteLine… Anyone faced such situation before?
The problem is most likely in the code that you are not showing. The type of issues that you describe is very common in multi-threading scenarios: everything comes down to timing, and timing is different when you change your code ever so slightly. In your particular case whatever value you are trying to access is there or not there depending on timing of what happening in other threads. It is simply possible that the value was not put there yet or was already deleted, when you code can’t find it, but is present when you code can’t see it.
It is impossible to say for sure, without seeing the rest of your code, especially the part that writes / deletes to / from the collection.
Few other things:
ContainsKeyin combination withTryGetValuedoes not make much sense, the way you wrote it. ‘TryGetValue’ exists so that you do NOT need to call ContainsKey: if value is there it will be returned to you straight away and if it’s not, the result of the method call will tell you this.