Is there a way to generate every time a 100% new GUID without any chance to collide within entire application?
Since I cannot answer my question in eight hours, I come up with the solution:
internal static class GuidGenerator
{
private static readonly HashSet<Guid> _guids = new HashSet<Guid>();
internal static Guid GetOne()
{
Guid result;
lock (_guids)
while (!_guids.Add(result = Guid.NewGuid())) ;
return result;
}
internal static void Utilize(Guid guid)
{
lock (_guids)
_guids.Remove(guid);
}
}
Is this code solves the problem within the app?
EDIT: Uh, its getting complicated. Thread safety kills the speed.
Sure. A GUID is just a 128-bit value. So use a 128-bit integer (e.g. represented by two
ulongvalues) and increment it. When you’ve reached the maximum value for the 128-bit integer type, you’ve generated all possible GUIDs. For example:Notes:
ulongvalues is a pain – I don’t like usingdo...while…Of course, this is in no way random…
In practice, as others have mentioned, the chances of collisions from
Guid.NewGuidare incredibly small.