您需要在单独的线程中执行此操作并在每次迭代之间休眠或使用计时器。
例如:
private int counter;
Timer t = new Timer();
Random random = new Random();
private void button1_Click(object sender, EventArgs e)
{
t.Interval = 100;
t.Tick += new EventHandler(t_Tick);
counter = 0;
t.Enabled = true;
txt3.Text = "";
}
void t_Tick(object sender, EventArgs e)
{
counter++;
int randomNumber = random.Next(100, 150);
txt3.Text = randomNumber.ToString();
if (counter >= 50)
{
t.Enabled = false;
}
}
请记住,这只是百万种方法中的一种。很多都很好
另一种方法是使用线程:
private void button1_Click(object sender, EventArgs e)
{
Thread t = new Thread(new ThreadStart(randomize));
t.Start();
}
private void randomize()
{
Random random = new Random();
txt3.Text = "";
for (int i = 0; i < 50; i++)
{
int randomNumber = random.Next(100, 150);
Invoke(new setTxtHandler(setText), randomNumber.ToString());
Thread.Sleep(100);
}
}
private void setText(string val)
{
txt3.Text = val;
}
private delegate void setTxtHandler(string val);