Reputation: 307
Here is simple code which has UI actions in the middle of backgroundworker. There is a form and a label "lbProgress" on it. When ProgressPercentage = 2, label is not changed but the action does.
private void Form1_Load(object sender, EventArgs e)
{
bw.WorkerSupportsCancellation = true;
bw.WorkerReportsProgress = true;
bw.DoWork += bw_DoWork;
bw.ProgressChanged += bw_ProgressChanged;
bw.RunWorkerCompleted += bw_RunWorkerCompleted;
}
int ii;
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
ii = 0;
bw.ReportProgress(1);
ii += 10;
Thread.Sleep(1000);
bw.ReportProgress(2); // here intended to do UI actions
bw.ReportProgress(3);
ii += 20;
Thread.Sleep(1000);
}
private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show(ii.ToString());
}
private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
lbProgress.Text = e.ProgressPercentage.ToString();
if (e.ProgressPercentage == 2)
{
this.Text += ", 00";
ii += 100;
Thread.Sleep(1000);
}
}
private void btRun_Click(object sender, EventArgs e)
{
bw.RunWorkerAsync();
}
Is it even possible to do large UI actions in the middle of backgroundworker thread using ProgressChanged event?
Upvotes: 0
Views: 87
Reputation: 11977
This is my answer to your question "Why do I see this behaviour?":
From the documentation of ReportProgress:
The call to the ReportProgress method is asynchronous and returns immediately.
So what happens is:
Upvotes: 2