码迷,mamicode.com
首页 > 其他好文 > 详细

BackgroundWroker使用方法备忘

时间:2017-05-25 13:30:18      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:evo   报告   completed   enabled   主线程   worker   namespace   gre   tar   

技术分享
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 = 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使用方法备忘

标签:evo   报告   completed   enabled   主线程   worker   namespace   gre   tar   

原文地址:http://www.cnblogs.com/yangmingyu/p/6903046.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!