后台代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms; namespace winform
{
public partial class fm : Form
{
BackgroundWorker worker;
public fm()
{
InitializeComponent();
worker = new BackgroundWorker();
worker.WorkerReportsProgress = true;
worker.WorkerSupportsCancellation = true;
//正式做事情的地方
worker.DoWork += new DoWorkEventHandler(DoWork);
//任务完称时要做的,比如提示等等
worker.ProgressChanged += new ProgressChangedEventHandler(ProgessChanged);
//任务进行时,报告进度
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(RunWorkerCompleted);
progressBar1.Maximum = ;
}
//调用 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;
//将异步任务进度的百分比赋给进度条
int value = int.Parse(e.UserState.ToString());
if (value % == )
textBox1.Text += "\r\n" + value;
else
textBox1.Text += "-" + value;
label1.Text = string.Format("完成{0}%", (value + ) * / progressBar1.Maximum);
} //当后台操作已完成、被取消或引发异常时发生
public void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
MessageBox.Show("取消了");
else
MessageBox.Show("完成!" + e.Result);
} private int ComputeFibonacci(object sender, DoWorkEventArgs e)
{ for (int i = ; i < ; i++)
{
//判断应用程序是否取消后台操作
if (worker.CancellationPending)
{
e.Cancel = true;
break;
}
//dowork function
worker.ReportProgress(i, i);
System.Threading.Thread.Sleep();
}
return -;
}
private void btnStart_Click(object sender, EventArgs e)
{
if (worker.IsBusy)
{
MessageBox.Show("已经执行异步操作");
return;
}
textBox1.Text = "";
label1.Text = "";
worker.RunWorkerAsync(); btnStart.Enabled = false; btnPause.Enabled = true;
} private void btnPause_Click(object sender, EventArgs e)
{
btnPause.Enabled = false; btnStart.Enabled = true; worker.CancelAsync();
}
}
}
页面效果: