我很想知道为什么 RunWorkerCompleted 实际上会在进度条完成之前更新 UI,textBox1 文本为“完成”。为什么会这样?
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 1; i <= 100; i++)
{
Thread.Sleep(10);
backgroundWorker1.ReportProgress(i);
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
textBox1.Text = "Done";
}
如果我使用
for (int i = 1; i <= 100; i++)
{
Thread.Sleep(20);
backgroundWorker1.ReportProgress(i);
MessageBox.Show(i.ToString());
}
然后它会做我所期望的
如果我在下面尝试这个,文本框会按预期更新,但进度条不会更新
public void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
textBox1.Text = e.ProgressPercentage.ToString();
progressBar1.Refresh();
}