加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 04:27:34 所属栏目:百科 来源:网络整理
导读:我在同事写的一个来源中看到这个功能 private String GetNewAvailableId(){ String newId = Guid.NewGuid().ToString(); while (clientsById.ContainsKey(newId)) { newId = Guid.NewGuid().ToString(); } return newId;} 我想知道有没有一个方案可能不是唯
我在同事写的一个来源中看到这个功能
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,同时也会将时间戳重复设置回相同的确切时间点.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读