Issue with Random string generator producing ident

2019-07-04 21:47发布

问题:

I use a random string generator, based on this: http://stackoverflow.com/questions/1344221/how-can-i-generate-random-8-character-alphanumeric-strings-in-c

Every now and then, it will generate a 20 chars len string like this aaaaaaaaaaaaaaaaaaaa when it needs to generate a 20 chars len string full of random chars (eg 63TSRVvbVDJiMNwneB5l), like if the C# Random object would return a value of 0 every time over the 20 iterations.

public static string GetRandomAlphaNumericString(int charCount)
{
  var result = new string(
      Enumerable.Repeat(CHARS, charCount)
                .Select(s =>
                {
                  var nxt = SHARED_RANDOM.Next(s.Length);
                  var rval = s[nxt];

                  return rval;
                })
                .ToArray());
  return result;
}

const string CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

public static Random SHARED_RANDOM = new Random(Guid.NewGuid().GetHashCode());

It doesn't make sense to me, what could I be overseeing in this generator ? The generator works OK, but every now and then, very rarely, it would perform like this generating a strike aaaaaaa strings for a short period of time.

I don't see a bug in the code, so to me it's 1 of 2 things, or the C# Random object is acting funny in some situations, returning 0 for a short period of time, or the CHARS const string changes from "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" to "a" in the assembly for some reason, for a short period of time.

I can't believe it could be either of the above, I prefer to believe that I'm overseeing something. Do you see or imagine how could this possibly be happening ?

UPDATE OCT 23 / 2017

Coded a test routine so if the GetRandomAlphaNumericString produces the evil aaaaa string, it will throw an error, but logs a quick report before.

The report generates 3 random numbers in a row, and adds it to the log:

    SHARED_RANDOM.Next(20);
    SHARED_RANDOM.Next(20);
    SHARED_RANDOM.Next(20);

The 3 numbers produced are 0, nice uh ?

This tells me that the issue is not the GetRandomAlphaNumericString, but the Random object itself. There is some sort of corruption that causes the object to return those results, so basically it could be anything ?!

标签: c#-4.0 random