You can reasonably expect that an UUID is unique and that the probability of collision is extremely low, as Amon already explained.
However, if life and death depend on this uniqueness, for example in large mission-critical systems that are meant to be up and running for very long time, you could consider the extra check to prevent harm. In the end, it's up to you to decide how to best balance the cost of the extra-verification of an improbable issue and the cost of the impact if the event would occur.
If you do the check, you should do it well. You may for example consider TryAdd()
. Not only is it shorter and conveys better your intent, it's also more suitable for concurrency:
do newID = Guid.NewGuid();
while (! dictionary.TryAdd(newID, value)); // check and add in one go
Because, your snippet would not work concurrently unless you'd use some locking scheme that would immediately create a concurrency bottleneck. What could for example go wrong if in theory two threads or nodes could generate at the same time a duplicate UUID (step 1), is that they would both not find their UUID as duplicate in your while
condition (step 2) as it not yet added, and one thread would fail when adding the key (step 3).