首页 > 代码库 > 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使用方法备忘
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。