I came across a strange problem today that i could understand the reason. Take the following console program.
internal class Program
{
private static void Main(string[] args)
{
string s1 = GenerateRandomCode(8);
string s2 = GenerateRandomCode(8);
string s3 = GenerateRandomCode(8);
}
public static string GenerateRandomCode(int length)
{
string charPool = "ABCDEFGOPQRSTUVWXY1234567890ZabcdefghijklmHIJKLMNnopqrstuvwxyz";
StringBuilder rs = new StringBuilder();
Random random = new Random();
for (int i = 0; i < length; i++)
{
rs.Append(charPool[(int)(random.NextDouble() * charPool.Length)]);
}
return rs.ToString();
}
}
If i put a breakpoint at the of the program and run the program the values of s1, s2, s3 are all the equal. Now if i put a breakpoint at s2 for example the value returned will be different.
Seems like some kind of concurrency issue? What’s going on?
Thanks
Random number generators are in fact not fully random: given the same seed value, multiple instances will generate the same random sequence.
Couldn’t say it better than the MSDN documentation for the Random constructor
So, in your case you need to keep the Random instance as a class-level field or a function parameter, and instantiate it only once.