http://www.cnblogs.com/xiaodsn/archive/2010/12/30/1921434.html
BackgroundWorker类是.net 2.0里新增加的一个类,对于需要长时间操作而不需要用户长时间等待的情况可以使用这个类。
* 注意确保在 DoWork 事件处理程序中不操作任何用户界面对象。而应该通过 ProgressChanged 和 RunWorkerCompleted 事件与用户界面进行通信。
* 它有几个属性:
* CancellationPending——指示应用程序是否已请求取消后台操作。
* IsBusy——指示 BackgroundWorker 是否正在运行异步操作
* WorkerReportsProgress——该值指示 BackgroundWorker 能否报告进度更新
* WorkerSupportsCancellation——该值指示 BackgroundWorker 是否支持异步取消
* 还有如下事件:
* DoWork——调用 RunWorkerAsync 时发生。
* ProgressChanged——调用 ReportProgress 时发生。
* RunWorkerCompleted——当后台操作已完成、被取消或引发异常时发生。
*
* 还有如下方法:
* CancelAsync——请求取消挂起的后台操作
* ReportProgress——引发 ProgressChanged 事件
* RunWorkerAsync——开始执行后台操作
所需控件如下: 三个textbox,两个button,一个进度条,一个backgroundWorker控件
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//设置计算按扭与取消按扭的使用属性以及进度条的进度值
this.button1.Enabled = false;
this.textBox3.Text = string.Empty;
this.button2.Enabled = true;
this.progressBar1.Value = 0;
backgroundWorker1.RunWorkerAsync(new CalcInput(int.Parse(this.textBox1.Text), int.Parse(this.textBox2.Text)));//开始执行后台操作
}
//当执行后台操作时,后台线程开始执行此操作
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
CalcInput input = (CalcInput)e.Argument;
//System.Threading.Thread.Sleep(5000);
//e.Result = input.x + input.y;
for (int i = 0; i < 10; i++)
{
System.Threading.Thread.Sleep(500);
backgroundWorker1.ReportProgress(i * 10);
if (backgroundWorker1.CancellationPending)
{
e.Cancel = true;
return;
}
}
e.Result = input.x + input.y;
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.progressBar1.Value = e.ProgressPercentage; //设置进度条的value值
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//this.textBox3.Text = e.Result.ToString();
//this.button2.Enabled = true;
//this.button1.Enabled = false;
//this.progressBar1.Value = 100;
if (e.Cancelled)
{
this.textBox3.Text = "cancelled";
}
else
{
this.textBox3.Text = e.Result.ToString();
}
this.button2.Enabled = true;
this.button1.Enabled = false;
this.progressBar1.Value = 100;
}
private void button2_Click(object sender, EventArgs e)
{
backgroundWorker1.CancelAsync();//执行此操作时,需将backgroundWorker1控件WorkerSupportCancellation属性设置为true
}
}
//记录两个文本框的值
public struct CalcInput
{
public CalcInput(int x, int Y)
{
this.x = x;
this.y = Y;
}
public int x;
public int y;
}