//frmA: 源窗体//------------------------------------------//引用using System.Threading;
BackgroundWorker worker;
public frmA() { InitializeComponent(); worker = new BackgroundWorker(); worker.DoWork += new DoWorkEventHandler(worker_DoWork); worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted); } ////// 异步 开始事件 /// /// /// private void worker_DoWork(object sender, DoWorkEventArgs e) { //需要执行的代码
Thread.Sleep(5000); //让进程上卡5秒钟
} ////// 事件: 异步执行完成后 /// /// /// private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { MessageBox.Show("执行完成。", "run", MessageBoxButtons.OK, MessageBoxIcon.Information); } //点击一个按钮后开始执行 private void btnA_Click(object sender, EventArgs e) {
//按钮要执行的代码放在 worker_DoWork 事件中执行
//异步执行开始 worker.RunWorkerAsync();
//显示进度窗体 frmB frm = new frmB(this.worker); frm.StartPosition = FormStartPosition.CenterScreen; frm.ShowDialog(this); }frmB: //里面放了一个loading.gif图片显示进度------------------------------------------------------------using System;using System.ComponentModel;using System.Windows.Forms;namespace test{ public partial class frmB: Form { public frmB(BackgroundWorker worker) { InitializeComponent(); worker.ProgressChanged +=new ProgressChangedEventHandler(worker_ProgressChanged); worker.RunWorkerCompleted +=new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted); } void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { this.Close(); } void worker_ProgressChanged(object sender, ProgressChangedEventArgs e) { //lblStatus.Text = ""; } //工作完成后执行的事件 public void OnProcessCompleted(object sender, EventArgs e) { this.Close(); } }
二:在弹出的窗体里显示backgroundWorker的进度
1, backgroundWorker1的WorkerReportsProgress属性设置为true2, 写如下事件 private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) { progressBar.Value = e.ProgressPercentage; } progressBar是进度条是你定义的变量..可以写在后台执行里面控制3 .在后台执行里面 backgroundWorker1.ReportProgress(50);其中50就是进度调的百分比.比如一个循环循环100次没次backgroundWorker1.ReportProgress(循环次数);那么效果出来 。。 哈哈