private String GetNewAvailableId() { String newId = Guid.NewGuid().ToString(); while (clientsById.ContainsKey(newId)) { newId = Guid.NewGuid().ToString(); } return newId; }
我想知道有没有一个方案可能不是唯一的?
该代码在多线程方案中使用,clientsById是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,同时也会将时间戳重复设置回相同的确切时间点.