using System;
using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;
namespace bcworker
{
public partial class Form1 : Form
{
//后台工作
private BackgroundWorker bw = new BackgroundWorker();
public Form1()
{
InitializeComponent();
//后台工作初始化
bw.WorkerReportsProgress = true;//报告进度
bw.WorkerSupportsCancellation = true;//支持取消
bw.DoWork += new DoWorkEventHandler(bgWorker_DoWork);//开始工作
bw.ProgressChanged += new ProgressChangedEventHandler(bgWorker_ProgessChanged);//进度改变事件
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgWorker_WorkerCompleted);//进度完成事件
}
private void btnStart_Click(object sender, EventArgs e)
{
//后台工作运行中,避免重入
if (bw.IsBusy) return;
bw.RunWorkerAsync("参数");//触发DoWork事件并异步执行,IsBusy置为True
}
//后台工作将异步执行
public void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
//(string)e.Argument == "参数";
for (int i = 0; i <= 100; i++)
{
if (bw.CancellationPending)
{//用户取消了工作
e.Cancel = true;
return;
}
else
{
bw.ReportProgress(i, "Working");//报告进度,触发ProgressChanged事件
Thread.Sleep(10);//模拟工作
}
}
}
//进度改变事件
public void bgWorker_ProgessChanged(object sender, ProgressChangedEventArgs e)
{
//(string)e.UserState=="Working"
progressBar1.Value = e.ProgressPercentage;//取得进度更新控件,不用Invoke了
}
//后台工作执行完毕,IsBusy置为False
public void bgWorker_WorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//e.Error == null 是否发生错误
//e.Cancelled 完成是由于取消还是正常完成
}
private void btnCancel_Click(object sender, EventArgs e)
{
if (bw.IsBusy) bw.CancelAsync();//设置CancellationPending属性为True
}
}
}
BackgroundWorker简明使用
最新推荐文章于 2024-10-10 15:31:57 发布