生成的顺序 GUID 有时不是顺序的

Generated Sequential GUIDs are sometimes not sequential

我有一个 C# 应用程序,它为我插入 table 的每一行生成一个顺序 GUID。我希望插入的 GUID 是连续的,但 有时 它们会破坏顺序(成块)。

示例:

这些 GUID 按插入顺序显示。

为什么创建这些 'sequential' GUID 时会出现如此大的序列中断?


用于生成顺序 GUID 的代码:

class NativeMethods
{
    [DllImport("rpcrt4.dll", SetLastError = true)]
    public static extern int UuidCreateSequential(out Guid guid);
}

public static Guid CreateSequentialGuid()
    {
        const int RPC_S_OK = 0;

        Guid guid;
        int result = NativeMethods.UuidCreateSequential(out guid);
        if (result == RPC_S_OK)
            return guid;
        else
            return Guid.NewGuid(); //<--In debugging, this statement never runs.
    }

循环中用于将新 GUID 和信息插入 table 的代码:

Guid mySequentialGUID = CreateSequentialGuid();
string[] row = { item1,
                 item2,
                 item3,  
                 sourceText,
                 encoding.ToString(),
                 mySequentialGUID.ToString()
             };
var listViewItem = new ListViewItem(row);
myListView.Items.Add(listViewItem);

编辑: 请查看此问题以了解顺序 GUID:

NewSequentialId()系统重启时重新开始。参见 here

Creates a GUID that is greater than any GUID previously generated by this function on a specified computer since Windows was started. After restarting Windows, the GUID can start again from a lower range, but is still globally unique. When a GUID column is used as a row identifier, using NEWSEQUENTIALID can be faster than using the NEWID function. This is because the NEWID function causes random activity and uses fewer cached data pages. Using NEWSEQUENTIALID also helps to completely fill the data and index pages.

我认为问题在于您假设 "sequential" 表示 "increment by one"。尽管您的示例表明有时会发生这种情况,但文档中并不能实际保证会发生这种情况。我们可以争论 "sequence" 的定义,或者这个函数的命名可能很糟糕甚至是错误的,但归根结底,根据文档,它似乎 100% 完全按照定义工作:

Creates a GUID that is greater than any GUID previously generated by this function

对于对 "sequential GUID" 的一般概念有疑问的人,请使用 "sequence" 的定义,即 "following a logical order" 并尝试记住 Melissa 病毒。这是 mildly document by this line:

For security reasons, UuidCreate was modified so that it no longer uses a machine's MAC address to generate UUIDs. UuidCreateSequential was introduced to allow creation of UUIDs using the MAC address of a machine's Ethernet card.

因此 "sequence" 基于 MAC 地址的 GUID。

回到 OP 的问题,对于为什么您的 GUID 每次都不会递增 1,我的最佳猜测是一个简单的事实,即您可能不是唯一调用此函数的人。这是一个核心 Windows 功能,必然会有其他组件、程序、服务等使用它。