C# · 12月 23, 2021

c# – 我需要验证GUID的唯一性吗?

我在同事写的一个来源中看到这个功能 private String GetNewAvailableId(){ String newId = Guid.NewGuid().ToString(); while (clientsById.ContainsKey(newId)) { newId = Guid.NewGuid().ToString(); } return newId;}


解决方法 这应该是完全不必要的 – GUID的全部要点是消除对这些检查的需要:-)


> GUIDs are globally unique,but substrings of GUIDs aren’t (The Old New Thing)

The goal of this algorithm is to use the combination of time and location (“space-time coordinates” for the relativity geeks out there) as the uniqueness key. However,timekeeping is not perfect,so there’s a possibility that,for example,two GUIDs are generated in rapid succession from the same machine,so close to each other in time that the timestamp would be the same. That’s where the uniquifier comes in. When time appears to have stood still (if two requests for a GUID are made in rapid succession) or gone backward (if the system clock is set to a new time earlier than what it was),the uniquifier is incremented so that GUIDs generated from the “second time it was five o’clock” don’t collide with those generated “the first time it was five o’clock”.