the following code is fairly straight forward – it fills a design surface with randomnly selected pixels – nothing special (ignore the XXXXXXX’s in the 2nd method for now).
private void PaintBackground()
{
Random rnd = new Random();
Bitmap b = new Bitmap(this.Width, this.Height);
for (int vertical = 0; vertical < this.Height; vertical++)
{
for (int horizontal = 0; horizontal < this.Width; horizontal++)
{
Color randomColour = GetRandomColor(rnd);
b.SetPixel(horizontal, vertical, randomColour);
}
}
Graphics g = this.CreateGraphics();
g.DrawImage(b, new Point(0, 0));
}
public Color GetRandomColor(Random rnd)
{
XXXXXXXXXXXXXXXX
byte r = Convert.ToByte(rnd.Next(0, 255));
byte g = Convert.ToByte(rnd.Next(0, 255));
byte b = Convert.ToByte(rnd.Next(0, 255));
return Color.FromArgb(255, r, g, b);
}
The question i have is this…
if you replace the XXXXXXXXX with “Random rnd = new Random();” the test pattern completely changes into horizontal bars of the same colour, and is therefore not random.
Come someone explain to me why this is?
As far as I can tell the only difference in the second attempt is that the GetRandomColour method creates and uses a new instance of the Random class but I don’t see how that makes horizontal bars..
From MSDN:
So given the same seed the Random instance will produce the same sequence of numbers. And in your example due to the finite resolution of the system clock, the Random instances were created using the same tick count as seed, resulting in the same sequence.
The consecutive calls to
GetRandomColor()are executed within one time slice of the system clock. To test this, try slowing the method down withThread.Sleep(1). You should see different colors being generated.