GUID 100%是唯一的吗?

它会在多个线程中保持唯一吗?


当前回答

理论上讲,不,它们不是唯一的。可以反复生成相同的guid。然而,这种情况发生的几率非常低,你可以假设它们是独一无二的。

我以前读到过,这种可能性非常低,你真的应该关注其他事情——比如你的服务器自燃或代码中的其他错误。也就是说,假设它是唯一的,不要构建任何“捕获”重复的代码——把时间花在更有可能发生的事情上(即任何其他事情)。

我尝试向我的博客读者(非技术家庭成员)描述guid的有用性。从那里(通过维基百科),生成重复GUID的几率:

1 / 2^128 1 / 340的十一分之一(别担心,十一分之一不在 测试) 1 / 3.4 × 10^38 1 / 340,000,000,000,000,000,000,000,000,000,000,000,000,000,000

其他回答

Eric Lippert写了一系列关于guid的非常有趣的文章。

There are on the order 230 personal computers in the world (and of course lots of hand-held devices or non-PC computing devices that have more or less the same levels of computing power, but lets ignore those). Let's assume that we put all those PCs in the world to the task of generating GUIDs; if each one can generate, say, 220 GUIDs per second then after only about 272 seconds -- one hundred and fifty trillion years -- you'll have a very high chance of generating a collision with your specific GUID. And the odds of collision get pretty good after only thirty trillion years.

GUID指南,第一部分 GUID指南,第二部分 GUID指南,第三部分

理论上讲,不,它们不是唯一的。可以反复生成相同的guid。然而,这种情况发生的几率非常低,你可以假设它们是独一无二的。

我以前读到过,这种可能性非常低,你真的应该关注其他事情——比如你的服务器自燃或代码中的其他错误。也就是说,假设它是唯一的,不要构建任何“捕获”重复的代码——把时间花在更有可能发生的事情上(即任何其他事情)。

我尝试向我的博客读者(非技术家庭成员)描述guid的有用性。从那里(通过维基百科),生成重复GUID的几率:

1 / 2^128 1 / 340的十一分之一(别担心,十一分之一不在 测试) 1 / 3.4 × 10^38 1 / 340,000,000,000,000,000,000,000,000,000,000,000,000,000,000

从统计上看,向导是独一无二的。两个不同的客户端生成相同Guid的几率非常小(假设Guid生成代码中没有错误)。你也可以担心由于宇宙射线导致的处理器故障,并决定今天2+2=5。

分配新guid的多个线程将获得唯一的值,但您应该知道您正在调用的函数是线程安全的。这是在哪个环境中?

如果你害怕相同的GUID值,那么把它们放在一起。

Guid.NewGuid().ToString() + Guid.NewGuid().ToString();

如果你太多疑,那就放三个。

I think that when people bury their thoughts and fears in statistics, they tend to forget the obvious. If a system is truly random, then the result you are least likely to expect (all ones, say) is equally as likely as any other unexpected value (all zeros, say). Neither fact prevents these occurring in succession, nor within the first pair of samples (even though that would be statistically "truly shocking"). And that's the problem with measuring chance: it ignores criticality (and rotten luck) entirely.

如果真的发生了,结果是什么?你的软件停止工作了吗?有人受伤了吗?有人死了吗?世界会爆炸吗?

临界性越极端,“概率”这个词就越难听。最后,链接guid(或XORing它们,或其他什么)是当你(主观地)认为你的特定临界性(和你的“幸运”感觉)是不可接受的时候所做的事情。如果它能毁灭世界,那么请代表我们所有没有参与大型强子对撞机核试验的人,不要使用guid或任何其他不确定的东西!