[英]c# how to use ProgressChanged event of BackgroundWorker to do UI actions in the middle of thread
Here is simple code which has UI actions in the middle of backgroundworker.这是一个简单的代码,它在后台工作人员的中间有 UI 操作。 There is a form and a label "lbProgress" on it.
上面有一个表格和一个标签“lbProgress”。 When ProgressPercentage = 2, label is not changed but the action does.
当 ProgressPercentage = 2 时,标签不会更改,但操作会更改。
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?甚至可以使用 ProgressChanged 事件在后台工作线程中间执行大型 UI 操作吗?
This is my answer to your question "Why do I see this behaviour?":这是我对您的问题“为什么我会看到这种行为?”的回答:
From the documentation of ReportProgress :从ReportProgress的文档中:
The call to the ReportProgress method is asynchronous and returns immediately.
对 ReportProgress 方法的调用是异步的并立即返回。
So what happens is:所以会发生什么:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.