c# 异步进度条组件BackgroundWorker

时间:2022-03-14 08:39:23
//控件事件调用DoWork()方法就行。

#region 进度条
private BackgroundWorker worker = null; private void DoWork(string outfile)
{
//显示进度条
ProgressForm progressForm = new ProgressForm();
progressForm.TopMost = true;
progressForm.Show(this); //准备进度条的记数
worker = new BackgroundWorker();
//指定提供进度通知
worker.WorkerReportsProgress = true;
//提供中断功能
worker.WorkerSupportsCancellation = true;
//线程的主要功能是处理事件
//开启线程执行工作
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
// Specify the function to use to handle progress
//指定使用的功能来处理进度
worker.ProgressChanged += new ProgressChangedEventHandler(progressForm.OnProgressChanged);
worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
//进度条结束完成工作
//1.工作完成
//2.工作错误异常
//3.取消工作
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(progressForm.OnProcessCompleted);
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
//如果进度条需要参数
//调用System.ComponentModel.BackgroundWorker.RunWorkerAsync
//传入你的参数至System.ComponentModel.BackgroundWorker.DoWork
//提取参数
//System.ComponentModel.DoWorkEventArgs.Argument worker.RunWorkerAsync(outfile);
} //单线程执行工作
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
try
{
worker_Doing((BackgroundWorker)sender, e);
}
catch (Exception ex)
{
//此处为异常处理,不能放到worker_Doing内部
e.Result = ex;
}
} //进行工作
private void worker_Doing(BackgroundWorker worker, DoWorkEventArgs e)
{
string outfile = e.Argument as string; //传入参数
int count = 500;
for (int i = ; i < count; i++)
{
//检查取消
if (worker.CancellationPending)
{
e.Cancel = true;
break;
}
else
{
//此处为具体的工作代码
//...

//进度报告
worker.ReportProgress((i + ) * ( / count), "进度信息");
//线程休眠
Thread.Sleep(); } } } //进度报告
private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
//此处可在窗口显示进度信息
//e.UserState as string
//...
} //工作完成状态
private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
string message = "";
if (e.Error != null)
{
message = e.Error.Message;
MessageBox.Show(this, message, "异常");
}
else if (e.Cancelled)
{
message = "操作被取消。";
MessageBox.Show(this, message, "提示");
}
else
{
if (e.Result == null)
{
message = "完成。";
MessageBox.Show(this, message, "信息");
}
else
{
message = (e.Result as Exception).Message;
MessageBox.Show(this, message, "异常");
}
} //此处代码为完成后的处理工作
//...
}
#endregion