BackgroundWorker解决“系统正在计算中,请稍后...”的办法

问题提出:

软件的某个功能计算量大,在计算过程中,无法和用户交互,故可以设置一提示,让用户等待!

问题解决:

使用BackgroundWorker控件

几个重要函数:

backgroundWorker.RunWorkerAsync():开始执行后台操作,引发DoWork事件

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { }:在这里执行费时的操作

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {   }:在这里执行显示计算结果的操作

CancelAsync():请求取消挂起的后台操作

具体实施办法:

(1)可设置一按钮btn为“点击查看运行结果”,在该btn的单击事件中,执行如下代码:backgroundWorker1.RunWorkerAsync();
pb.ShowDialog();
 

注意上述两个语句顺序不能颠倒!

//pb为一form,里面是诸如“系统正在运行,请稍后......”的文字或图片

(2)在_DoWork函数里,执行程序计算代码

(3)在_RunWorkerCompleted函数里,执行如下代码:

this.pb.Visible = false;
this.pb.Close();
frmViewResults fvr = new frmViewResults();//计算结果显示form
fvr.ShowDialog();

如果运行时间过长,可以设置一“取消”按钮,让用户退出!

主要代码如下:

开始计算:

       pb = new progressBar(this);
        backgroundWorker1.RunWorkerAsync();
        pb.ShowDialog();

DoWork()方法:

//先判断用户是否取消了

if (this.backgroundWorker1.CancellationPending)
{
            e.Cancel = true;

}
else
{
            //最费时的代码
}

RunWorkerCompleted()方法:

if (e.Cancelled)
{
          this.pb.Visible = false;
          this.pb.Close();
          // The user canceled the operation.
          MessageBox.Show("您取消了计算!", "提示信息:", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);

}
else if (e.Error != null)
{
           this.pb.Visible = false;
           this.pb.Close();
           // There was an error during the operation.
           MessageBox.Show("计算错误!", "提示信息:", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);

}
else
{
           this.pb.Visible = false;
           this.pb.Close();

           this.label1.Text = "";
           this.label1.Text = "调度结果查看!";

}

“取消”按钮事件:

public void cancelAsyncButton_Click()
{
        // Cancel the asynchronous operation.
          this.backgroundWorker1.CancelAsync();            

}

更为详细的“取消”操作,请参见:http://www.dotblogs.com.tw/billchung/archive/2009/05/30/8597.aspx

解决为_DoWork()方法传递参数的问题???

某些操作中,可能在_DoWork()中要传入参数,可以采用如下方法解决:

backgroundWorker1.RunWorkerAsync(要传递的数据);

在_DoWork()中获得数据:e.Argument.ToString();

原文地址:https://www.cnblogs.com/zhihai/p/2384745.html