https://blog.csdn.net/feiyang5260/article/details/90272311
BackgroundWorker控件实现,不会假死
BackgroundWorker可在单独的线程上执行操作
步骤如下:
(1)主窗体设计,为主窗体添加一个BackgroundWorker控件和按钮控件
(2)主窗体后台代码Form1.cs
主窗体记得要绑定事件:
namespace progress_backgroundworker { public partial class Form1 : Form { public Form1() { InitializeComponent(); this.backgroundWorker1.WorkerReportsProgress = true; //设置能报告进度更新 this.backgroundWorker1.WorkerSupportsCancellation = true; //设置支持异步取消 } private void button1_Click(object sender, EventArgs e) { this.backgroundWorker1.RunWorkerAsync(); //运行backgroundWorker组件 ProgressForm form = new ProgressForm(this.backgroundWorker1); //显示进度条窗体 form.ShowDialog(this); form.Close(); } //在另一个线程上开始运行(处理进度条) private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker worker = sender as BackgroundWorker; for (int i = 0; i < 100; i++) { System.Threading.Thread.Sleep(100); worker.ReportProgress(i); if (worker.CancellationPending) //获取程序是否已请求取消后台操作 { e.Cancel = true; break; } } } private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { if (e.Error != null) { MessageBox.Show(e.Error.Message); } else if (e.Cancelled) { MessageBox.Show("取消"); } else { MessageBox.Show("完成"); } } } }
(3)子窗体设计
(4)子窗体代码实现ProgressForm.cs
namespace progress_backgroundworker { public partial class ProgressForm : Form { private BackgroundWorker backgroundWorker1; //ProgressForm窗体事件(进度条窗体) public ProgressForm(BackgroundWorker bgWork) { InitializeComponent(); // add my code this.backgroundWorker1 = bgWork; //绑定进度条改变事件 this.backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged); //绑定后台操作完成,取消,异常时的事件 this.backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted); } void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) { this.progressBar1.Value = e.ProgressPercentage; //获取异步任务的进度百分比 } void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { //this.Close(); //执行完之后,直接关闭页面 } //取消 private void btnCancel_Click(object sender, EventArgs e) { this.backgroundWorker1.CancelAsync(); //请求取消挂起的后台操作 this.btnCancel.Enabled = false; this.Close(); } } }