<pre name="code" class="csharp">FormA,用于监控耗时事务的进度。
FormB,用来处理耗时事务,并且通知界面A。包括开始和取消操作,
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WinBackgroundWorker
{
public partial class FormB : Form
{
public FormB()
{
InitializeComponent();
backgroundWorker1.WorkerReportsProgress = true;//能否报告进度更新
backgroundWorker1.WorkerSupportsCancellation = true; //是否支持异步取消
}
/// <summary>
/// 添加 DoWork 事件的事件处理程序。 在此事件处理程序中调用耗时的操作。
///
/// 注意
/// 您必须非常小心,确保在 DoWork 事件处理程序中不操作任何用户界面对象。
/// 而应该通过 ProgressChanged 和 RunWorkerCompleted 事件与用户界面进行通信。
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
//TODO:耗时的操作
//把所有后台事务的代码放在这里执行
//使用worker.ReportProgress,设置一个[0,100]之间的整数进度值
BackgroundWorker worker = sender as BackgroundWorker;
for (int i = 1; i <= 10;i++ )
{
if (worker.CancellationPending==true) //指示应用程序取消后台操作
{
e.Cancel = true;
break;
}
else
{
System.Threading.Thread.Sleep(1000); //耗时操作
worker.ReportProgress(i * 10); //报告进度值
}
}
}
/// <summary>
/// 进度改变
/// 当辅助线程指示某些操作已经进行时,触发
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
FormA A = (FormA)this.Owner;
//获得当前窗体的所有者FormA,然后对A.PVALUE和LB_RESULTTEXT这2个公有属性进行设置进度
A.LB_RESULTTEXT = "进度值:" + e.ProgressPercentage.ToString() + "%";
A.PVALUE = e.ProgressPercentage;
}
/// <summary>
/// 结束或终止任务
/// 当辅助线程完成时(无论成功、失败、引发异常、取消等),触发
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
FormA A = (FormA)this.Owner;
//获得当前窗体的所有者FormA,然后对A.PVALUE和LB_RESULTTEXT这2个公有属性进行设置进度
if (e.Cancelled==true)
{
A.LB_RESULTTEXT = "进度值:" + "取消操作";
A.PVALUE = 0;
}
else if (e.Error!=null)
{
A.LB_RESULTTEXT = "错误:" + e.Error.Message;
A.PVALUE= 0;
}
else
{
A.LB_RESULTTEXT = "进度值:100%,完成";
A.PVALUE =100;
}
}
private void btnStart_Click(object sender, EventArgs e)
{
if (backgroundWorker1.IsBusy!=true)
{
//开始执行后台异步操作
backgroundWorker1.RunWorkerAsync();
}
}
private void btnCanel_Click(object sender, EventArgs e)
{
if (backgroundWorker1.WorkerSupportsCancellation==true)
{
backgroundWorker1.CancelAsync();//取消异步操作
}
}
private void FormB_FormClosing(object sender, FormClosingEventArgs e)
{
if (backgroundWorker1.IsBusy==true)
{
MessageBox.Show("后台线程正在执行异步操作!请等待操作完成后再关闭窗体!");
e.Cancel = true;
return;
}
}
}
}
启动时,启动FormA,由A启动B界面。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace WinBackgroundWorker
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FormA());
}
}
}
示例运行界面如下: