我使用当前时钟滴答作为随机数生成的种子。随机数用于伪 GUID,并且在我的数据库中进行检查将确保它在返回之前不存在。平均而言,在进程的生命周期内,该方法将被连续调用大约 10k 次。
我担心的是,可能会连续生成相同的号码,从而导致对我的数据库进行多次不必要的递归调用以检查相同的 ID。如果可能的话我想避免这种情况。测试这个场景的最佳方法是什么?
如果重要的话,应用程序是 .NET 4,数据库是 SQL Server 2008。
private static string GenerateUniqueDelId()
{
// Generate a random integer using the current number of clock ticks as seed.
// Then prefix number with "DEL" and date, finally padding random integer with leading zeros for a fixed 25-character total length.
int seed = (int)DateTime.Now.Ticks;
Random number = new Random(seed);
string id = string.Format("DEL{0}{1}", DateTime.Today.ToString("yyyyMMdd"), number.Next().ToString("D14"));
// Lookup record with generated ID in Sesame. If one exists, call method recursively.
string query = "SELECT * FROM Lead WHERE Esm_Id = @Esm_Id";
SqlParameter[] parameters = { new SqlParameter("@Esm_Id", id) };
if (DataManager.GetRow(query, parameters, DelConnection.Sesame) != null) return GenerateUniqueDelId();
// Otherwise, return ID.
return id;
} //// End GenerateUniqueDelId()
您的担忧是正确的:您应该移动您的创作Random
实例超出您的方法主体 - 否则您将多次使用相同的值重新播种,从而产生相同的数字序列。
而且你有点重新发明轮子:默认的构造函数Random
类已经使用当前时钟时间作为默认种子。
问题是为什么不避免所有这些而只在数据库端使用自动生成的 Guid 呢?
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)