【问题标题】:Using clock ticks as random number seed使用时钟滴答作为随机数种子
【发布时间】:2012-06-09 20:13:54
【问题描述】:

我使用当前时钟滴答作为随机数生成的种子。随机数用于伪 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()

【问题讨论】:

  • 如果你要到 sql server 检查它们的存在 - 为什么你不能首先在那里生成它们?
  • 作为使用随机数的替代方法,您可以使用Identity 列吗?
  • 为什么不直接使用 GUID。我不喜欢重新制作轮子。

标签: c# sql-server random


【解决方案1】:

引用乔恩·斯基特的话

当您在 Stack Overflow 上的问题标题中看到“随机”一词时,您几乎可以保证这将是与无数类似问题相同的基本问题。本文着眼于为什么随机性会导致如此多的问题,以及如何解决这些问题。

查看他关于随机数生成器的文章

http://csharpindepth.com/Articles/Chapter12/Random.aspx

基本上他的解决方案如下:

using System;
using System.Threading;

public static class RandomProvider
{    
    private static int seed = Environment.TickCount;

    private static ThreadLocal<Random> randomWrapper = new ThreadLocal<Random>(() =>
        new Random(Interlocked.Increment(ref seed))
    );

    public static Random GetThreadRandom()
    {
        return randomWrapper.Value;
    }
}

【讨论】:

  • 我仍然收到使用 Environment.TickCount 作为种子的副本。我最终使用了 (int)DateTime.UtcNow.Ticks 并且还没有收到任何重复的结果。
  • @JoshDeLong - 这就是随机性的有趣之处;它不承诺永远不会提供重复的内容:)
【解决方案2】:

您的担心是对的:您应该将 Random 实例的创建移出您的方法主体 - 否则您将多次使用相同的值重新播种,从而导致相同的数字序列。

另外你有点重新发明轮子:Random 类的默认构造函数已经使用当前时钟时间作为默认种子。

问题是您为什么不避免所有这些,而只在数据库端使用自动生成的 Guid?

【讨论】:

  • ID 正在外部供应商的系统中使用,并且具有特定的格式标准:长度为 25 个字符,前缀为 3 个字母字符和 yyyyMMdd 格式的日期。我只能玩剩下的 14 个角色。
  • 哦,关于默认的 Random 构造函数,感谢您提供的信息。不知道它默认使用时钟滴答 - 我一定会在我的代码中更新它!
  • 我最终将 Random 移到了循环之外,这样我就可以将它传递给 GenerateUniqueDelId(Random generator)。
猜你喜欢
  • 2016-12-06
  • 1970-01-01
  • 1970-01-01
  • 2014-11-02
  • 1970-01-01
  • 1970-01-01
  • 2015-08-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多