http://msdn.microsoft.com/en-us/library/system.guid.aspx
How does it work? How does it guarantee unique ID? Does it only rely on probability or is there another trick? Can 开发者_C百科I always trust it to give unique id or what are cases where I should avoid guid?
Here's a fun little program:
class Program
{
static void Main(string[] args)
{
var guids = new HashSet<string>();
var sw = Stopwatch.StartNew();
while(true)
{
var guid = Guid.NewGuid().ToString().Replace("-", "").Substring(0, 16);
if (guids.Contains(guid)) break;
guids.Add(guid);
}
Console.WriteLine("Duplicate found in {0} ms, after {1} items.", sw.ElapsedMilliseconds, guids.Count);
Console.ReadLine();
}
}
I bet you'll run out of memory before it finds a dupe ;)
Edit: Even when using only half a Guid.
A Guid doesn't guarantee a unique ID, it just has a very low probability of generating a duplicate one.
First of all, the Guid structure does not guarantee anything by itself you can create many guids yourself by an explicit constructor: var myGuid = new Guid(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 });
That way you can create how many identical Guids you like.
But I suppose you mean Guids created with the static method Guid.NewGuid()
. In the remarks section it is noted that the probability that the Guid is all zeros or equal to another Guid is low.
You can also read the RFC that describes how the randomness in a Guid is created.
It uses a special algorithm designed to produce unique IDs. Yes, they might collide, but that's highly unlikely. Also see this closely related question.
The .NET Guid.NewGuid() actually calls the function CoCreateGuid found in ole32.dll which is part of Windows "core".
The CoCreateGuid is calling the function UuidCreate which creates such thing, that is actually the "low level" of Guid.
From what I've read and understand (not official answer) it's generated using combination of MAC address of the machine and the current system time (amount of milliseconds that passed since 1/1/1970) and probably also random number but I'm not sure about this.
Avoid using GUID in the cases described under "Security Considerations" section in the link posted by Albin.
All your other questions has been answered in the other answers, no point to repeat it.:)
精彩评论