如何生成绝对唯一的GUID? [英] How to generate absolutely unique GUID's?

查看:64
本文介绍了如何生成绝对唯一的GUID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以每次生成100%的新GUID而不会在整个应用程序中发生冲突?

Is there a way to generate every time a 100% new GUID without any chance to collide within entire application?

由于我无法在8个小时内回答问题,因此提出了解决方案:

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?

嗯,它变得越来越复杂.线程安全会降低速度.

Uh, its getting complicated. Thread safety kills the speed.

推荐答案

好的.GUID只是一个128位的值.因此,请使用128位整数(例如,用两个 ulong 值表示)并将其递增.当达到128位整数类型的最大值时,就生成了所有可能的GUID.例如:

Sure. A GUID is just a 128-bit value. So use a 128-bit integer (e.g. represented by two ulong values) and increment it. When you've reached the maximum value for the 128-bit integer type, you've generated all possible GUIDs. For example:

public IEnumerable<Guid> GetAllGuids()
{
    unchecked
    {
        byte[] buffer = new byte[16];
        ulong x = 0UL;
        do
        {
           byte[] high = BitConverter.GetBytes(x);
           Array.Copy(high, 0, buffer, 0, 8);
           ulong y = 0UL;
           do
           {
               y++;
               byte[] low = BitConverter.GetBytes(y);
               Array.Copy(low, 0, buffer, 8, 8);
               yield return new Guid(buffer);
           } while (y != 0UL);
           x++;
        } while (x != 0UL);
    }
}

注意:

  • 这肯定不如可能有效.
  • 遍历所有可能的 ulong 值很痛苦-我不喜欢 使用 do ... while ...
  • 如评论中所述,这将产生无效的 UUID s
  • This is definitely not as efficient as it might be.
  • Iterating over all possible ulong values is a pain - I don't like using do...while...
  • As noted in comments, this will produce values which are not valid UUIDs

当然,这绝不是随机的...

Of course, this is in no way random...

在实践中,正如其他人提到的那样, Guid.NewGuid 发生碰撞的可能性非常小.

In practice, as others have mentioned, the chances of collisions from Guid.NewGuid are incredibly small.

这篇关于如何生成绝对唯一的GUID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆