首页 > 代码库 > BackgroundWroker使用方法备忘

BackgroundWroker使用方法备忘

技术分享
using System;
using System.ComponentModel;
using System.Windows.Forms;
using System.Threading;

namespace WindowsFormsApplication1
{
publicpartialclass Form1 : Form
{
public Form1()
{
InitializeComponent();
worker =new BackgroundWorker();
worker.DoWork+=new DoWorkEventHandler(worker_DoWork);
worker.ProgressChanged+=new ProgressChangedEventHandler(worker_ProgressChanged);
worker.RunWorkerCompleted+=new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
worker.WorkerReportsProgress =true; //允许进度显示
worker.WorkerSupportsCancellation =true; //允许运行中取消
}

BackgroundWorker worker;

privatevoid Form1_Load(object sender, EventArgs e)
{

}

privatevoid worker_DoWork(object sender, DoWorkEventArgs e)
{
for (int i =0; i <300; i++)
{
Thread.Sleep(100);
//每隔一段时间就向主线程报告进度,以便更新进度条。
//多数情况下,你只需要发送一个整数去更新即可
worker.ReportProgress(i/3);
if (worker.CancellationPending)
{
//如果任务被取消
e.Cancel =true;
worker.ReportProgress(0);
return;
}
}
}

privatevoid worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
pbarThis.Value = http://www.mamicode.com/e.ProgressPercentage;
lblText.Text ="已经处理了 "+ pbarThis.Value.ToString() +"%";
}

privatevoid worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
lblText.Text ="任务取消";
}
elseif (e.Error !=null)
{
lblText.Text ="发生错误";
}
else
{
lblText.Text ="任务完成";
}
btnStart.Enabled =true;
btnCancel.Enabled =false;
}

privatevoid btnStart_Click(object sender, EventArgs e)
{
btnStart.Enabled =false;
btnCancel.Enabled =true;

//通知主线程开始进行数据处理
worker.RunWorkerAsync();
}

privatevoid btnCancel_Click(object sender, EventArgs e)
{
if (worker.IsBusy)
{

worker.CancelAsync();
}
}
}
}
技术分享

BackgroundWroker使用方法备忘