Using Clock Pulses as Random Numbers

I use current clock ticks as a seed to generate random numbers. A random number is used in the pseudo GUID, and checking in my database will make sure that it does not exist before returning. On average, this method will be called approximately 10k times in a row throughout the process.

My concern is that the same number can be generated from the back, which leads to a lot of unnecessary recursive calls for my database, checking for the same identifier. I would like to avoid this if possible. What is the best way to test this scenario?

If it matters, the application is .NET 4 and the 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()
+5
source
2

: Random , , .

, : Random .

, Guid ?

+10

: Jon Skeet

"" " ", , , . , .

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;
    }
}
+6

All Articles