我很想知道为什么RunWorkerCompleted实际上会在进度条完成之前更新UI,textBox1文本为“Done”。为什么会这样?
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();
}
答案 0 :(得分:1)
可能会出现一些滞后现象。
ReportProgress()
机制可能使用BeginInvoke()
,因此更新会排队。这会有点延迟,但通常不会引人注意。
ProgressBar有自己的内部更新机制。这似乎故意延迟了几百毫秒的反馈。我想有些用户会进行缩放调整。