Will it only return false if the dictionary does not contain a value for the given key or will it also return false due to thread race conditions, like another thread adds/updates something?
Question in code:
ConcurrentDictionary<int, string> cd = new ConcurrentDictionary<int, string>();
// This might fail if another thread is adding with key value of 1.
cd.TryAdd(1, "one");
// Will this ever fail if no other thread ever removes with the key value of 1?
cd.TryRemove(1);
Edit: I think that it only will return false if it does not contain a value for the given key, but want to be absolutely sure.
While Mitch is right that a ConcurrentDictionary
is not vulnerable to race conditions, I think the answer to the question you are asking is that yes, if the key is present, TryRemove
will work and will return true
.
In the code you posted, there's no way that TryRemove
would return false
since cd
is a local variable not accessed anywhere else. But if some code elsewhere were given a reference to this ConcurrentDictionary
object and were removing keys on a separate thread, then it's possible that TryRemove
could return false
, even here -- but only because the key was already removed, not because some other action is being performed on the dictionary and the key is somehow "stuck" there.