(请参见 受保护的属性 )
名称 说明 CancellationPending 获取一个值,指示应用程序是否已请求取消后台操作。 Container 获取 IContainer,它包含 Component。 (从 Component 继承。) IsBusy 获取一个值,指示 BackgroundWorker 是否正在运行异步操作。 Site 获取或设置 Component 的 ISite。 (从 Component 继承。) WorkerReportsProgress 获取或设置一个值,该值指示 BackgroundWorker 能否报告进度更新。 WorkerSupportsCancellation 获取或设置一个值,该值指示 BackgroundWorker 是否支持异步取消。
代码 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 BackgroundWork{ public partial class Form1 : Form { public Form1() { InitializeComponent(); this .backgroundWorker.WorkerReportsProgress = true ; this .backgroundWorker.WorkerSupportsCancellation = true ; } /// <summary> /// 处理耗时操作,不能与UI交互(不能出现UI控件) /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void backgroundWorker_DoWork( object sender, DoWorkEventArgs e) { for ( int i = 0 ; i < 1001 ; i ++ ) { // --backgroundWorker.CancelAsync方法请求取消后台操作后, // --backgroundWorker.CancelAsync属性为True if ( this .backgroundWorker.CancellationPending) { e.Cancel = true ; // 取消事件 break ; } Thread.Sleep( 10 ); this .backgroundWorker.ReportProgress(i, " 处理中 " ); // e.Result = i ; } } /// <summary> /// 耗时操作过程中与UI交互,比如显示进度 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void backgroundWorker_ProgressChanged( object sender, ProgressChangedEventArgs e) { this .progressBar1.Value = e.ProgressPercentage; int per = ( this .progressBar1.Value / 10 ); this .label1.Text = per.ToString() + " % " ; this .Text = e.UserState.ToString(); } private void backgroundWorker_RunWorkerCompleted( object sender, RunWorkerCompletedEventArgs e) { if (e.Cancelled) { MessageBox.Show( " 操作被取消 " ); this .progressBar1.Value = 0 ; this .label1.Text = " 0% " ; } else { MessageBox.Show( " 完成 " ); this .Text = " 完成 " ; } } private void button1_Click( object sender, EventArgs e) { this .backgroundWorker.RunWorkerAsync(); } private void button2_Click( object sender, EventArgs e) { this .backgroundWorker.CancelAsync(); } }}
转载于:https://www.cnblogs.com/willwayer/archive/2009/12/29/1634629.html
相关资源:WinForm中BackgroundWorker控件用法简单实例