Go homepage(回首页) Upload pictures (上传图片) Write articles (发文字帖)
The author:(作者)qqpublished in(发表于) 2014/7/11 9:15:50 C#中BackgroundWorker组件的用法以及实例
C#中BackgroundWorker组件的用法以及实例
BackgroundWorker组件功能在运行程序时,有些操作可能需要很长的执行时间,例如,图像下载、Web服务调用和文件下载、上传等。这些操作可能导致用户界面在操作运行时挂起,如果此时需要用户界面的响应,可以使用BackgroundWorker组件,在不同于应用程序的主用户界面线程的另一线程上异步(“在后台”)执行耗时的操作。图1所示为BackgroundWorker组件。图1 BackgroundWorker组件2.属性BackgroundWorker组件常用属性及说明如表1所示。表1 BackgroundWorker 组件常用属性及说明下面详细介绍WorkerSupportsCancellation属性,该属性用于获取或设置一个值,该值指示BackgroundWorker是否支持异步取消。语法: public bool WorkerSupportsCancellation { get; set; }属性值:如果BackgroundWorker支持取消,则为True;否则为False。默认值为False。示例WorkerSupportsCancellation属性的使用本示例主要是使用BackgroundWorker组件的WorkerSupportsCancellation属性,判断是否取消了异步操作。程序主要代码如下: if (this.backgroundWorker1.WorkerSupportsCancellation){// The user canceled the operation.MessageBox.Show("后台操作取消");}★★★★★主程序文件完整程序代码★★★★★ using System;using System.Collections.Generic;using System.Windows.Forms;namespace _8_25{static class Program{/// /// 应用程序的主入口点。/// [STAThread]static void Main(){Application.EnableVisualStyles();Application.SetCompatibleTextRenderingDefault(false);Application.Run(new frmBackgroundWorker());}}}★★★★★frmBackgroundWorker窗体设计文件完整程序代码★★★★★ using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.Threading;namespace _8_25{public partial class frmBackgroundWorker : Form{public frmBackgroundWorker(){InitializeComponent();}private int numberToCompute = 0;private int highestPercentageReached = 0;private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e){e.Result = ComputeFibonacci((int)e.Argument, backgroundWorker1, e);}private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e){this.progressBar1.Value = e.ProgressPercentage;}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;startAsyncButton.Enabled = true;cancelAsyncButton.Enabled = false;}private void startAsyncButton_Click(object sender, EventArgs e){resultLabel.Text = String.Empty;this.numericUpDown1.Enabled = false;this.startAsyncButton.Enabled = false;this.cancelAsyncButton.Enabled = true;numberToCompute = (int)numericUpDown1.Value;highestPercentageReached = 0;this.backgroundWorker1.RunWorkerAsync(numberToCompute);}private void cancelAsyncButton_Click(object sender, EventArgs e){this.backgroundWorker1.CancelAsync();this.progressBar1.Value = 0;this.startAsyncButton.Enabled = true;this.cancelAsyncButton.Enabled = false;this.resultLabel.Text = "No Result";}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)numberToCompute * 100);if (percentComplete > highestPercentageReached){highestPercentageReached = percentComplete;worker.ReportProgress(percentComplete);}}return result;}private void frmBackgroundWorker_Load(object sender, EventArgs e){}}}★★★★★frmBackgroundWorker窗体设计文件完整程序代码★★★★★
赞