backgroundworker控件 下载本文

*

* 还有如下方法:

* CancelAsync——请求取消挂起的后台操作

* ReportProgress——引发 ProgressChanged 事件 * RunWorkerAsync——开始执行后台操作 * **/

namespace BackgroundWorkerDemo {

public partial class MainForm : Form {

private

BackgroundWorker

worker

=

BackgroundWorker(); public MainForm() {

InitializeComponent();

worker.WorkerReportsProgress = true; worker.WorkerSupportsCancellation = true; //正式做事情的地方 worker.DoWork+=new DoWorkEventHandler(DoWork);

//任务完称时要做的,比如提示等等

new

worker.ProgressChanged += new

ProgressChangedEventHandler(ProgessChanged); //任务进行时,报告进度 worker.RunWorkerCompleted

+=

new

RunWorkerCompletedEventHandler(CompleteWork); }

//调用 RunWorkerAsync 时发生

public void DoWork(object sender, DoWorkEventArgs e) {

e.Result = ComputeFibonacci(worker, e);//当ComputeFibonacci(worker, e)返回时,异步过程结束 }

//调用 ReportProgress 时发生 public

void

ProgessChanged(object

sender,

ProgressChangedEventArgs e) {

this.progressBar1.Value = e.ProgressPercentage; }

//当后台操作已完成、被取消或引发异常时发生 public

void

CompleteWork(object

sender,

RunWorkerCompletedEventArgs e) {

MessageBox.Show(\完成!\ }

private

int

ComputeFibonacci(object

DoWorkEventArgs e) {

for (int i = 0; i < 1000; i++) {

if (worker.CancellationPending) {

e.Cancel = true; } else {

worker.ReportProgress(i); }

System.Threading.Thread.Sleep(10); }

return -1; }

sender,

private void btnStart_Click(object sender, EventArgs e) {

worker.RunWorkerAsync(); btnStart.Enabled = false; btnPause.Enabled = true; }

private void btnPause_Click(object sender, EventArgs e) {

btnPause.Enabled = false; btnStart.Enabled = true; worker.CancelAsync(); } } }