C# · 12月 23, 2021

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

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

我想知道有没有一个方案可能不是唯一的?
该代码在多线程方案中使用,clientsById是GUID和对象的字典

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

您可能会很有趣的阅读这个有趣的帖子在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”.

您可能遇到碰撞的唯一真正的方法是,如果有人在同一台机器上生成数千个GUID,同时也会将时间戳重复设置回相同的确切时间点.