可能重复:
Random number generator not working the way I had planned (C#)
您好,
下面是我正在编写的小应用程序的完整代码 - 它返回一个包含字母数字代码的ArrayList。我遇到的问题是,当“踩踏”代码时,e.Result会正确返回,每个项目都不同。但是,如果我让应用程序在没有断点的情况下运行,我只会得到同一个变量的多个实例:
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);
}
}
}
}
任何人都可以解释为什么当我通过踩踏我的方式有效地减慢过程时结果是可以的但是当它在没有停止/减速的情况下运行时不正确?
非常感谢
答案 0 :(得分:3)
backgroundWorker1_DoWork
中的循环非常快,以致Random
中生成的generateCode
对象始终使用相同的值进行播种,从而生成相同的值。不要重新创建Random
对象,而是将其分配给类的构造函数中的实例变量,并仅使用该对象。
答案 1 :(得分:2)
每次需要随机数时,都不应创建新的Random
对象。
Random rnd = new Random();
使用当前时间初始化LFSR,当程序全速运行时,连续多次使用相同的“当前时间”。