Possible Duplicate:
Random number generator not working the way I had planned (C#)
Hi,
Below is the complete code for a small app I am writing - it returns an ArrayList of alphanumeric codes. The problem I have is that when 'stepping' through the code the e.Result is returned correctly with each item being different. However, if I let the app run without the breakpoints I just get multiple instances of the same variable back:
public partial class AlphaNum : Form
{
public AlphaNum()
{
InitializeComponent();
// Initialise BackGroundWorker Reporting
backgroundWorker1.WorkerReportsProgress = true;
// Initialise BackGroundWorker Cancel
backgroundWorker1.WorkerSupportsCancellation = true;
}
private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
button1.Enabled = false;
}
private int RandomNumber(int min, int max)
{
Random random = new Random();
return random.Next(min, max);
}
public string RandomString(Random r, int len)
{
string str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
StringBuilder sb = new StringBuilder();
while ((len--) > 0)
sb.Append(str[(int)(r.NextDouble() * str.Length)]);
return sb.ToString();
}
private string generateCode()
{
Random rnd = new Random();
int length = int.Parse(stringLength.Text);
string code = "";
code = RandomString(rnd, length);
return code;
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
int quantity = int.Parse(quantityRequired.Text);
ArrayList codes = new ArrayList();
string myText = "";
for (int a = 0; a < quantity; a++)
{
myText = generateCode();
codes.Add(myText);
backgroundWorker1.ReportProgress(((100 / quantity) * a));
}
e.Result = codes;
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage; //update progress bar
//Console.WriteLine(time);
//in this example, we log that optional additional info to textbox
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
button1.Enabled = true;
ArrayList codes = new ArrayList();
codes = (ArrayList)e.Result;
for (int i = 0; i < codes.Count; i++ )
{
outputText.Text += codes[i].ToString();
outputText.AppendText(Environment.NewLine);
}
}
}
}
Can anyone explain why the result is okay when I effectively slow the process down by stepping my way through but incorrect when it runs without being stopped/slowed down?
Many Thanks
The loop in
backgroundWorker1_DoWork
is so fast that theRandom
object generated ingenerateCode
is always seeded with the same value, thus producing the same values. Don't recreate theRandom
object but assign one to an instance variable in the constructor of your class and only use that one.You shouldn't create a new
Random
object every time you need a random number.uses the current time to initialize the LFSR, when the program runs at full speed, the same "current time" gets used many times in a row.