using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace BackGroundWorker组件
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.backgroundWorker1.DoWork += new DoWorkEventHandler(background1_DoWork);
this.backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundworker1_ProgressChange);
this.backgroundWorker1.RunWorkerCompleted+=new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
this.btnStart.Click += new EventHandler(startAsyncButton_Click);
this.btnCancel.Click += new EventHandler(btnCancel_Click);
}
private int numberToComputer = 0;
private int highPercentReched = 0;
private void background1_DoWork(object sender, DoWorkEventArgs e)
{
e.Result = ComputeFibonacci((int)e.Argument, this.backgroundWorker1, e);//为组件的运行结果赋值
}
long ComputeFibonacci(int n, BackgroundWorker worker, DoWorkEventArgs e)
{
if(n<0 || n>91)
{
throw new ArgumentException("value must be>=0 and <=91", "n");//抛出异常
}
long result = 0;
if (worker.CancellationPending)
{
e.Cancel = true;
}
else
{
if (n < 2)
{
result = 1;
}
else
{
result = ComputeFibonacci(n - 1, worker, e) + ComputeFibonacci(n - 2, worker, e);
}
int percentComplete = (int)((float)n / (float)numberToComputer * 100);
if (percentComplete > highPercentReched)
{
highPercentReched = percentComplete;
worker.ReportProgress(percentComplete);
}
}
return result;
}
private void backgroundworker1_ProgressChange(object sender, ProgressChangedEventArgs e)
{
this.progressBar1.Value = e.ProgressPercentage;//为进度条赋值
}
/// <summary>
/// 当辅助线程完成(无论是成功,失败还是取消)时引发
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void backgroundWorker1_RunWorkerCompleted(object sender,RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
MessageBox.Show(e.Error.Message);
}
else if (e.Cancelled)
{
resultLabel.Text = "Canceled";
}
else
{
resultLabel.Text = e.Result.ToString();
}
this.numericUpDown1.Enabled = true;
btnStart.Enabled = true;
btnCancel.Enabled = false;
}
/// <summary>
/// 开始启用异步操作
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void startAsyncButton_Click(object sender, EventArgs e)
{
resultLabel.Text = string.Empty;
this.numericUpDown1.Enabled = false;
this.btnStart.Enabled = false;
this.btnCancel.Enabled = true;
numberToComputer = (int)numericUpDown1.Value;
highPercentReched = 0;
backgroundWorker1.RunWorkerAsync(numberToComputer);
}
/// <summary>
/// 请求取消后台挂起的操作
/// </summary>
/// <param name="obj"></param>
/// <param name="e"></param>
private void btnCancel_Click(object obj, EventArgs e)
{
this.backgroundWorker1.CancelAsync();
btnCancel.Enabled = false;
}
}
}
BackgroundWorker组件的使用
最新推荐文章于 2023-09-05 11:12:05 发布