C# BackgroundWorker,在DoWork里更新控件内容
一般情况下不可以直接在BackgroundWorker的DoWork事件中更新 UI 控件
在BackgroundWorker的DoWork事件处理方法中,代码是在后台线程中执行的。而在 Windows Forms 等应用程序中,大多数 UI 控件都不是线程安全的,直接从非 UI 线程(后台线程)更新 UI 控件可能会导致不可预测的行为,如程序崩溃、显示异常等。
正确的做法是使用ProgressChanged事件来更新 UI
BackgroundWorker提供了一种安全的机制来报告进度并更新 UI。在DoWork事件处理方法中,可以通过调用BackgroundWorker的ReportProgress方法。
例如:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
for (int i = 1; i <= 100; i++)
{
if (worker.CancellationPending)
{
e.Cancel = true;
break;
}
else
{
// 模拟工作进度,这里可以是实际的耗时操作
System.Threading.Thread.Sleep(100);
worker.ReportProgress(i);
}
}
}然后在ProgressChanged事件处理方法中更新 UI 控件,如更新进度条的值或显示相关信息:
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
label1.Text = $"进度:{e.ProgressPercentage}%";
}所以,不建议在DoWork事件中直接更新 UI 控件,而应该通过ReportProgress和ProgressChanged事件来安全地更新 UI。
转载请注明出处。