Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate absolutely unique GUID's?

Tags:

c#

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.

like image 220
AgentFire Avatar asked Nov 02 '11 13:11

AgentFire


People also ask

How do you create a unique GUID?

To Generate a GUID in Windows 10 with PowerShell, Type or copy-paste the following command: [guid]::NewGuid() . This will produce a new GUID in the output. Alternatively, you can run the command '{'+[guid]::NewGuid(). ToString()+'}' to get a new GUID in the traditional Registry format.

Are GUIDs really unique?

A GUID is a unique number that can be used as an identifier for anything in the universe, but unlike ISBN there is no central authority - the uniqueness of a GUID relies on the algorthm that was used to generate it.

How do I make a global unique identifier?

Individuals and organizations can create GUIDs using a free GUID generator that is available online. An online generator constructs a unique GUID according to RFC 4122. When creating a GUID, users should note the timestamp, clock sequence and the node ID -- such as a Media Access Control (MAC) address.

How many unique GUIDs are there?

However, you can try to calculate the chance of creating two GUIDs that are identical and you get the idea: a GUID has 128 bits, hence, there are 2128 distinct GUIDs – much more than there are stars in the known universe.


1 Answers

No, there isn't any way to generate absolutely unique GUIDs. There are only 3.40282367 × 1038 possible GUIDs so as galaxies collide so will these identifiers. Even for a single application, it depends on how many GUIDs the application has. Unless your app is bigger than all of Google's indexers combined, you don't need to lose sleep over this. Just use Guid.NewGuid().

like image 106
Mark Cidade Avatar answered Oct 27 '22 04:10

Mark Cidade