BackgroundWorker类允许您在单独的线程上执行某个可能导致用户界面(UI)停止响应的耗时操作(比如文件下载数据库事务等),并且想要一个响应式的UI来反应当前耗时操作的进度。
引用命名空间:using System.ComponentModel;
public partial class RegisterWindow : Window
{
BackgroundWorker worker;
public RegisterWindow()
{
InitializeComponent();
}
/// <summary>
/// 检查更新
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Btn_CheckUpdate_Click(object sender, RoutedEventArgs e)
{
worker = new BackgroundWorker();
//是否报告进度更新
worker.WorkerReportsProgress = true;
//是否支持异步取消
worker.WorkerSupportsCancellation = true;
//一般规则是您不能从该事件触摸 UI 中的任何内容。
worker.DoWork += worker_DoWork;
//在worker_DoWork内调用ReportProgress()方法,该方法依次引发ProgressChanged事件,可以从该事件更新 UI。
worker.ProgressChanged += worker_ProgressChanged;
//当操作完成或取消时执行RunWorkerCompleted()
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
//防止重复执行异步操作引发错误
if (bgWorker.IsBusy)
return;
//开始执行后台操作
worker.RunWorkerAsync();
//this.Close();
//System.Windows.Application.Current.Shutdown();
}
//运行在非UI上,无法直接修改UI内容。
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
class1 model = new class1();
model.id = 10021;
model.hint = "正在加载请稍后······";
//并且还可以传对象
worker.ReportProgress(0, model);
for (int i = 1; i <= 100; i++)
{
//调用worker.ReportProgress(i)方法,执行worker_ProgressChanged()方法
worker.ReportProgress(i);
Thread.Sleep(400);
}
}
//编辑UI内容
void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.Dispatcher.Invoke(new Action(() =>
{
ProgressBar.Value = i.ProgressPercentage;
}));
}
//当以上操作完成之后,执行此方法,该方法是可以编辑UI内容
void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("更新成功");
}
class class1
{
public int id { get; set; }
public string hint { get; set; }
}
}