BackgroundWorker简介

   BackgroundWorker在winfrom中有对应控件,该有三个事件:DoWork 、ProgressChanged 和 RunWorkerCompleted。

在程序中调用RunWorkerAsync方法则会启动DoWork事件的事件处理,当在事件处理过程中,调用 ReportProgress方法则会启动ProgressChanged事件的事件处理,而当DoWork事件处理完成时,则会触发RunWorkerCompleted事件。您必须非常小心,确保在 DoWork 事件处理程序中不操作任何用户界面对象(否则仍会停止响应)。而应该通过 ProgressChanged和 RunWorkerCompleted 事件与用户界面进行通信。

实现waitefrom界面的窗体,改界面自己设计。

 /// <summary>
/// 当辅助线程指示某些操作已经进行时引发
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
int progress = e.ProgressPercentage;
this.progressBar1.Value = progress;
//label1.Content = string.Format("{0}", progress);
} /// <summary>
/// 操作开始时在另一个线程上运行的事件处理程序
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{ } /// <summary>
/// 当辅助线程完成(无论是成功,失败或者取消)时引发
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
this.DialogResult = DialogResult.OK;
}

调用waitefrom船体代码(DoWork事件不要重复使用)

  protected virtual void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker bw = sender as BackgroundWorker;
for (int i = ; i < ; i++)
{
System.Threading.Thread.Sleep();
WaiteForm1 f = e.Argument as WaiteForm1;
f.bw.ReportProgress(i);
bw.ReportProgress(i);
}
object a = e.Argument;
object b = e.Cancel;
e.Result = "";
} private void button1_Click(object sender, EventArgs e)
{
WaiteForm1 wa = new WaiteForm1(); //执行DoWork事件可传入执行的参数
wa.bw.RunWorkerAsync(wa); wa.bw.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
//wa.bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
wa.ShowDialog(this);
this.Text = "";
}
05-07 14:59