Possible Duplicate:
Why does this Random Number Generator not random?
I have this test program:
static void Main(string[] args)
{
var randomNumbers = new Dictionary<int, int>();
foreach (var s in Enumerable.Range(1, 500))
{
var rand = Rand5();
if (!randomNumbers.ContainsKey(rand))
randomNumbers.Add(rand, 1);
else
randomNumbers[rand] += 1;
}
randomNumbers
.ToList()
.ForEach(x => Console.WriteLine("{0}: {1}", x.Key, x.Value));
Console.ReadLine();
}
static int Rand5()
{
System.Threading.Thread.Sleep(1);
return new Random().Next(1, 6);
}
If I comment out System.Threading.Thread.Sleep(1);
, I get
5: 500
But if I uncomment that line, I do get random numbers.
2: 87
4: 94
1: 116
5: 108
3: 95
Why does the line of code matter? Thanks!