gpt4 book ai didi

c# - 生成的顺序 GUID 有时不是顺序的

转载 作者:行者123 更新时间:2023-11-30 14:24:12 25 4
gpt4 key购买 nike

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

例子:

Break in sequence

这些 GUID 按插入顺序显示。

为什么创建这些“顺序”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 和信息插入表中的代码:

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

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

最佳答案

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

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

对于对“顺序 GUID”的一般概念有疑问的人,请使用关于“遵循逻辑顺序”的“序列”定义,并尝试记住 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.

所以“序列”是基于 MAC 地址的 GUID。

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

关于c# - 生成的顺序 GUID 有时不是顺序的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41899426/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com