C# Windows窗体-显示更改的值

C# Windows窗体-显示更改的值,c#,.net,winforms,C#,.net,Winforms,在表单中我试图在文本框中显示更改的值: private void MyButton_Click(object sender, EventArgs e) { for (int i = 0; i < 10; i++) { Start(i); } } public void Start(int i) { textBox1.Text = i.ToString(); Thread.Sleep(200); } private void MyB

表单中
我试图在
文本框中显示更改的值

private void MyButton_Click(object sender, EventArgs e)
{
    for (int i = 0; i < 10; i++)
    {
        Start(i);
    } 
}
public void Start(int i)
{
    textBox1.Text = i.ToString();
    Thread.Sleep(200);
}
private void MyButton\u单击(对象发送者,事件参数e)
{
对于(int i=0;i<10;i++)
{
启动(i);
} 
}
公共无效开始(int i)
{
textBox1.Text=i.ToString();
睡眠(200);
}

仅显示循环的最后一个值。为什么?

有一个称为UI线程的线程,负责更新GUI。单击按钮时,此事件将在UI线程上运行。因此,
Start
函数也在UI线程上运行。UI线程正忙于运行
Start
函数,因此在
Start
函数完成之前,它没有机会更新文本框。
Start
函数完成后,UI线程将文本框更新为最后一个值

您需要做的是在另一个线程上运行
Start
函数,这样UI线程就可以自由地更新文本框。有几种方法可以做到这一点。这里有一个例子:

private System.Windows.Forms.Timer _timer;
private int _timer_i;

public Form1()
{
  InitializeComponent();

  _timer = new System.Windows.Forms.Timer()
  {
    Enabled = false,
    Interval = 200
  };
  _timer.Tick += _timer_Tick;
}

private void _timer_Tick(object sender, EventArgs e)
{
  textBox1.Text = _timer_i.ToString();
  _timer_i++;
  if (_timer_i >= 10)
  {
    _timer.Stop();
  }
}

private void button1_Click(object sender, EventArgs e)
{
  _timer.Stop();
  _timer_i = 0;
  _timer.Start();
}

有一个称为UI线程的线程,负责更新GUI。单击按钮时,此事件将在UI线程上运行。因此,
Start
函数也在UI线程上运行。UI线程正忙于运行
Start
函数,因此在
Start
函数完成之前,它没有机会更新文本框。
Start
函数完成后,UI线程将文本框更新为最后一个值

您需要做的是在另一个线程上运行
Start
函数,这样UI线程就可以自由地更新文本框。有几种方法可以做到这一点。这里有一个例子:

private System.Windows.Forms.Timer _timer;
private int _timer_i;

public Form1()
{
  InitializeComponent();

  _timer = new System.Windows.Forms.Timer()
  {
    Enabled = false,
    Interval = 200
  };
  _timer.Tick += _timer_Tick;
}

private void _timer_Tick(object sender, EventArgs e)
{
  textBox1.Text = _timer_i.ToString();
  _timer_i++;
  if (_timer_i >= 10)
  {
    _timer.Stop();
  }
}

private void button1_Click(object sender, EventArgs e)
{
  _timer.Stop();
  _timer_i = 0;
  _timer.Start();
}

因为GUI从来没有机会刷新。使用计时器或后台线程。@谢谢,我已经使用了textBox1.Update(),它正在工作,但我不确定它是否是正确的解决方案。不,它不是。请参阅我的第二句话。StackOverflow已经广泛地讨论了这个主题。因为GUI从来没有机会刷新。使用计时器或后台线程。@谢谢,我已经使用了textBox1.Update(),它正在工作,但我不确定它是否是正确的解决方案。不,它不是。请参阅我的第二句话。StackOverflow已经广泛地介绍了这个主题。