0

I am not sure I fully understand TryGet method.

When does it exactly return false - when the internal lock is locked and it means I should use while if I want to get value (knowing it's there)?

Or this while is somehow embedded in this function internals and returning false means - there is no such a key in dictionary?

NB. Is this right for all other methods of ConcurrentDictionary - TryAdd etc?

Martin Liversage
  • 104,481
  • 22
  • 209
  • 256
bgee
  • 989
  • 2
  • 13
  • 19
  • 1
    How do you know its there for sure? Can you add more context about the usage and what you are trying to achieve? In general, if TryGet returns false, then you need to assume the item is not in the collection. – Itsik Nov 07 '17 at 07:52
  • Why not have a look at the internals or the documentation? ILSpy or Reflector will provide you with the source code (de-compiled from the DLL so it won't look exactly the same as the original but the logic will remain the same) or like I said check out the documentation on from Microsoft, the new docs website is pretty good – Dave Nov 07 '17 at 07:52

2 Answers2

5

TryGet will block until any locks are cleared. It is typically a very short block (it does not take long to add or remove a key). It will then return true if the key/value is present and false otherwise. It will not wait for the key to be added.

If you expect the key to be populated by another thread, and you're not sure if it's finished, you could use a while loop. But I've never had to do that. I think if you find yourself writing a while loop in this circumstance you may have a suboptimal design. Consider using GetOrAdd to retrieve the value, which allows you to supply a function to populate the key if it is not present, e.g.

var user = dictionary.GetOrAdd("User", (key) => GetUser());

If you don't want to use GetOrAdd and you absolutely have to wait for that other thread to finish, try to refactor your code so you have a reference to its SynchronizationContext or its Task. Then a/wait it. That will yield execution in a more efficient manner than a while loop.

John Wu
  • 50,556
  • 8
  • 44
  • 80
2

The documentation states

Returns Boolean true if the key was found in the ConcurrentDictionary; otherwise, false.

Jesper Bangsholt
  • 544
  • 4
  • 11