Using clock ticks as random number seed

2020-03-23 02:25发布

I'm using the current clock ticks as a seed for random number generation. The random number is used in a pseudo GUID and a check in my database will make sure it doesn't already exist before returning. On average, this method will be called around 10k times in succession during the life of the process.

My concern is that an identical number might be generated back to back resulting in multiple unnecessary recursive calls to my database checking for the same ID. I'd like to avoid this if possible. What is the best way to test this scenario?

If it matters, application is .NET 4 and database is 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()

2条回答
萌系小妹纸
2楼-- · 2020-03-23 02:52

You are right in your concern: You should move the creation of your Random instance out of your method body - otherwise you will re-seed with the same value many times which results in the same number sequence.

Also you are kinda re-inventing the wheel: the default constructor of the Random class already uses the current clock time as default seed.

The question is why don't you avoid all of this and just use an auto-generated Guid on the database side?

查看更多
Bombasti
3楼-- · 2020-03-23 02:53

Quoting Jon Skeet

When you see the word "random" in a question title on Stack Overflow you can almost guarantee it will be the same fundamental problem as countless similar questions. This article takes a look at why randomness causes so many problems, and how to address them.

Check his article about random number generators

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

basically his solution looks like:

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;
    }
}
查看更多
登录 后发表回答