BackgroundWorker 类

注意:此类在 .NET Framework 2.0 版中是新增的。

在单独的线程上执行操作。

命名空间:​System.ComponentModel

程序集:​System(在 system.dll 中)


 语法 C#

public class BackgroundWorker : Component


C++

public ref class BackgroundWorker : public Component


备注



BackgroundWorker​ 类允许您在单独的专用线程上运行操作。耗时的操作(如下载和数据库事务)在长时间运行时可能会导致用户界面 (UI) 似乎处于停止响应状态。如果您需要能进行响应的用户界面,而且面临与这类操作相关的长时间延迟,则可以使用 ​BackgroundWorker​ 类方便地解决问题。

若要在后台执行耗时的操作,请创建一个 ​BackgroundWorker​,侦听那些报告操作进度并在操作完成时发出信号的事件。可以通过编程方式创建 ​BackgroundWorker​,也可以将它从“工具箱”的“组件”选项卡中拖到窗体上。如果在 Windows 窗体设计器中创建 ​BackgroundWorker​,则它会出现在组件栏中,而且它的属性会显示在“属性”窗口中。

若要设置后台操作,请为 ​​DoWork​​​ 事件添加一个事件处理程序。在此事件处理程序中调用耗时的操作。若要启动该操作,请调用 ​​RunWorkerAsync​​​。若要收到进度更新通知,请对 ​​ProgressChanged​​​ 事件进行处理。若要在操作完成时收到通知,请对 ​​RunWorkerCompleted​​ 事件进行处理。



注意


您必须非常小心,确保在 ​DoWork​ 事件处理程序中不操作任何用户界面对象。而应该通过 ​ProgressChanged​ 和 ​RunWorkerCompleted​ 事件与用户界面进行通信。

BackgroundWorker​ 事件不跨 ​​AppDomain​​ 边界进行封送处理。请不要使用 ​BackgroundWorker​ 组件在多个 ​AppDomain​ 中执行多线程操作。



如果后台操作需要参数,请在调用 ​RunWorkerAsync​ 时给出参数。在 ​DoWork​ 事件处理程序内部,可以从 ​​DoWorkEventArgs.Argument​​ 属性中提取该参数。

有关 ​BackgroundWorker​ 的更多信息,请参见 ​​如何:在后台运行操作​​。



注意


应用于此类的 ​​HostProtectionAttribute​​​ 属性 (Attribute) 具有以下 ​​Resources​​​ 属性 (Property) 值:​​SharedState​​。​HostProtectionAttribute​ 不影响桌面应用程序(这些应用程序通常通过双击图标、键入命令或在浏览器中输入 URL 来启动)。有关更多信息,请参见 ​HostProtectionAttribute​ 类或 ​​SQL Server 编程和宿主保护属性​​。


 示例


下面的代码示例演示如何使用 ​BackgroundWorker​ 类异步执行耗时的操作。该操作计算选定的斐波纳契数,在计算过程中报告进度更新,并允许取消挂起的计算。

C#


BackgroundWorker 类_floatusing

 System;

BackgroundWorker 类_float

using  System.Collections;

BackgroundWorker 类_float

using  System.ComponentModel;

BackgroundWorker 类_float

using  System.Drawing;

BackgroundWorker 类_float

using  System.Threading;

BackgroundWorker 类_float

using  System.Windows.Forms;

BackgroundWorker 类_float

BackgroundWorker 类_float

namespace  BackgroundWorkerExample

BackgroundWorker 类_system_09BackgroundWorker 类_system_10

... {    

BackgroundWorker 类_object_11    public class FibonacciForm : System.Windows.Forms.Form

BackgroundWorker 类_system_12BackgroundWorker 类_object_13    ...{    

BackgroundWorker 类_object_11        private int numberToCompute = 0;

BackgroundWorker 类_object_11        private int highestPercentageReached = 0;

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11        private System.Windows.Forms.NumericUpDown numericUpDown1;

BackgroundWorker 类_object_11        private System.Windows.Forms.Button startAsyncButton;

BackgroundWorker 类_object_11        private System.Windows.Forms.Button cancelAsyncButton;

BackgroundWorker 类_object_11        private System.Windows.Forms.ProgressBar progressBar1;

BackgroundWorker 类_object_11        private System.Windows.Forms.Label resultLabel;

BackgroundWorker 类_object_11        private System.ComponentModel.BackgroundWorker backgroundWorker1;

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11        public FibonacciForm()

BackgroundWorker 类_system_12BackgroundWorker 类_object_13        ...{    

BackgroundWorker 类_object_11            InitializeComponent();

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11            InitializeBackgoundWorker();

BackgroundWorker 类_forms_30        }

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11        // Set up the BackgroundWorker object by 

BackgroundWorker 类_object_11        // attaching event handlers. 

BackgroundWorker 类_object_11        private void InitializeBackgoundWorker()

BackgroundWorker 类_system_12BackgroundWorker 类_object_13        ...{

BackgroundWorker 类_object_11            backgroundWorker1.DoWork += 

BackgroundWorker 类_object_11                new DoWorkEventHandler(backgroundWorker1_DoWork);

BackgroundWorker 类_object_11            backgroundWorker1.RunWorkerCompleted += 

BackgroundWorker 类_object_11                new RunWorkerCompletedEventHandler(

BackgroundWorker 类_object_11            backgroundWorker1_RunWorkerCompleted);

BackgroundWorker 类_object_11            backgroundWorker1.ProgressChanged += 

BackgroundWorker 类_object_11                new ProgressChangedEventHandler(

BackgroundWorker 类_object_11            backgroundWorker1_ProgressChanged);

BackgroundWorker 类_forms_30        }

BackgroundWorker 类_object_11    

BackgroundWorker 类_object_11        private void startAsyncButton_Click(System.Object sender, 

BackgroundWorker 类_object_11            System.EventArgs e)

BackgroundWorker 类_system_12BackgroundWorker 类_object_13        ...{

BackgroundWorker 类_object_11            // Reset the text in the result label.

BackgroundWorker 类_object_11            resultLabel.Text = String.Empty;

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11            // Disable the UpDown control until 

BackgroundWorker 类_object_11            // the asynchronous operation is done.

BackgroundWorker 类_object_11            this.numericUpDown1.Enabled = false;

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11            // Disable the Start button until 

BackgroundWorker 类_object_11            // the asynchronous operation is done.

BackgroundWorker 类_object_11            this.startAsyncButton.Enabled = false;

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11            // Enable the Cancel button while 

BackgroundWorker 类_object_11            // the asynchronous operation runs.

BackgroundWorker 类_object_11            this.cancelAsyncButton.Enabled = true;

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11            // Get the value from the UpDown control.

BackgroundWorker 类_object_11            numberToCompute = (int)numericUpDown1.Value;

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11            // Reset the variable for percentage tracking.

BackgroundWorker 类_object_11            highestPercentageReached = 0;

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11            // Start the asynchronous operation.

BackgroundWorker 类_object_11            backgroundWorker1.RunWorkerAsync(numberToCompute);

BackgroundWorker 类_forms_30        }

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11        private void cancelAsyncButton_Click(System.Object sender, 

BackgroundWorker 类_object_11            System.EventArgs e)

BackgroundWorker 类_system_12BackgroundWorker 类_object_13        ...{   

BackgroundWorker 类_object_11            // Cancel the asynchronous operation.

BackgroundWorker 类_object_11            this.backgroundWorker1.CancelAsync();

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11            // Disable the Cancel button.

BackgroundWorker 类_object_11            cancelAsyncButton.Enabled = false;

BackgroundWorker 类_forms_30        }

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11        // This event handler is where the actual,

BackgroundWorker 类_object_11        // potentially time-consuming work is done.

BackgroundWorker 类_object_11        private void backgroundWorker1_DoWork(object sender, 

BackgroundWorker 类_object_11            DoWorkEventArgs e)

BackgroundWorker 类_system_12BackgroundWorker 类_object_13        ...{   

BackgroundWorker 类_object_11            // Get the BackgroundWorker that raised this event.

BackgroundWorker 类_object_11            BackgroundWorker worker = sender as BackgroundWorker;

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11            // Assign the result of the computation

BackgroundWorker 类_object_11            // to the Result property of the DoWorkEventArgs

BackgroundWorker 类_object_11            // object. This is will be available to the 

BackgroundWorker 类_object_11            // RunWorkerCompleted eventhandler.

BackgroundWorker 类_object_11            e.Result = ComputeFibonacci((int)e.Argument, worker, e);

BackgroundWorker 类_forms_30        }

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11        // This event handler deals with the results of the

BackgroundWorker 类_object_11        // background operation.

BackgroundWorker 类_object_11        private void backgroundWorker1_RunWorkerCompleted(

BackgroundWorker 类_object_11            object sender, RunWorkerCompletedEventArgs e)

BackgroundWorker 类_system_12BackgroundWorker 类_object_13        ...{

BackgroundWorker 类_object_11            // First, handle the case where an exception was thrown.

BackgroundWorker 类_object_11            if (e.Error != null)

BackgroundWorker 类_system_12BackgroundWorker 类_object_13            ...{

BackgroundWorker 类_object_11                MessageBox.Show(e.Error.Message);

BackgroundWorker 类_forms_30            }

BackgroundWorker 类_object_11            else if (e.Cancelled)

BackgroundWorker 类_system_12BackgroundWorker 类_object_13            ...{

BackgroundWorker 类_object_11                // Next, handle the case where the user canceled 

BackgroundWorker 类_object_11                // the operation.

BackgroundWorker 类_object_11                // Note that due to a race condition in 

BackgroundWorker 类_object_11                // the DoWork event handler, the Cancelled

BackgroundWorker 类_object_11                // flag may not have been set, even though

BackgroundWorker 类_object_11                // CancelAsync was called.

BackgroundWorker 类_object_11                resultLabel.Text = "Canceled";

BackgroundWorker 类_forms_30            }

BackgroundWorker 类_object_11            else

BackgroundWorker 类_system_12BackgroundWorker 类_object_13            ...{

BackgroundWorker 类_object_11                // Finally, handle the case where the operation 

BackgroundWorker 类_object_11                // succeeded.

BackgroundWorker 类_object_11                resultLabel.Text = e.Result.ToString();

BackgroundWorker 类_forms_30            }

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11            // Enable the UpDown control.

BackgroundWorker 类_object_11            this.numericUpDown1.Enabled = true;

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11            // Enable the Start button.

BackgroundWorker 类_object_11            startAsyncButton.Enabled = true;

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11            // Disable the Cancel button.

BackgroundWorker 类_object_11            cancelAsyncButton.Enabled = false;

BackgroundWorker 类_forms_30        }

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11        // This event handler updates the progress bar.

BackgroundWorker 类_object_11        private void backgroundWorker1_ProgressChanged(object sender,

BackgroundWorker 类_object_11            ProgressChangedEventArgs e)

BackgroundWorker 类_system_12BackgroundWorker 类_object_13        ...{

BackgroundWorker 类_object_11            this.progressBar1.Value = e.ProgressPercentage;

BackgroundWorker 类_forms_30        }

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11        // This is the method that does the actual work. For this

BackgroundWorker 类_object_11        // example, it computes a Fibonacci number and

BackgroundWorker 类_object_11        // reports progress as it does its work.

BackgroundWorker 类_object_11        long ComputeFibonacci(int n, BackgroundWorker worker, DoWorkEventArgs e)

BackgroundWorker 类_system_12BackgroundWorker 类_object_13        ...{

BackgroundWorker 类_object_11            // The parameter n must be >= 0 and <= 91.

BackgroundWorker 类_object_11            // Fib(n), with n > 91, overflows a long.

BackgroundWorker 类_object_11            if ((n < 0) || (n > 91))

BackgroundWorker 类_system_12BackgroundWorker 类_object_13            ...{

BackgroundWorker 类_object_11                throw new ArgumentException(

BackgroundWorker 类_object_11                    "value must be >= 0 and <= 91", "n");

BackgroundWorker 类_forms_30            }

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11            long result = 0;

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11            // Abort the operation if the user has canceled.

BackgroundWorker 类_object_11            // Note that a call to CancelAsync may have set 

BackgroundWorker 类_object_11            // CancellationPending to true just after the

BackgroundWorker 类_object_11            // last invocation of this method exits, so this 

BackgroundWorker 类_object_11            // code will not have the opportunity to set the 

BackgroundWorker 类_object_11            // DoWorkEventArgs.Cancel flag to true. This means

BackgroundWorker 类_object_11            // that RunWorkerCompletedEventArgs.Cancelled will

BackgroundWorker 类_object_11            // not be set to true in your RunWorkerCompleted

BackgroundWorker 类_object_11            // event handler. This is a race condition.

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11            if (worker.CancellationPending)

BackgroundWorker 类_system_12BackgroundWorker 类_object_13            ...{   

BackgroundWorker 类_object_11                e.Cancel = true;

BackgroundWorker 类_forms_30            }

BackgroundWorker 类_object_11            else

BackgroundWorker 类_system_12BackgroundWorker 类_object_13            ...{   

BackgroundWorker 类_object_11                if (n < 2)

BackgroundWorker 类_system_12BackgroundWorker 类_object_13                ...{   

BackgroundWorker 类_object_11                    result = 1;

BackgroundWorker 类_forms_30                }

BackgroundWorker 类_object_11                else

BackgroundWorker 类_system_12BackgroundWorker 类_object_13                ...{   

BackgroundWorker 类_object_11                    result = ComputeFibonacci(n - 1, worker, e) + 

BackgroundWorker 类_object_11                             ComputeFibonacci(n - 2, worker, e);

BackgroundWorker 类_forms_30                }

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11                // Report progress as a percentage of the total task.

BackgroundWorker 类_object_11                int percentComplete = 

BackgroundWorker 类_object_11                    (int)((float)n / (float)numberToCompute * 100);

BackgroundWorker 类_object_11                if (percentComplete > highestPercentageReached)

BackgroundWorker 类_system_12BackgroundWorker 类_object_13                ...{

BackgroundWorker 类_object_11                    highestPercentageReached = percentComplete;

BackgroundWorker 类_object_11                    worker.ReportProgress(percentComplete);

BackgroundWorker 类_forms_30                }

BackgroundWorker 类_forms_30            }

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11            return result;

BackgroundWorker 类_forms_30        }

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11

BackgroundWorker 类_object_13BackgroundWorker 类_system_12        Windows Form Designer generated code#region Windows Form Designer generated code

BackgroundWorker 类_object_11        

BackgroundWorker 类_object_11        private void InitializeComponent()

BackgroundWorker 类_system_12BackgroundWorker 类_object_13        ...{

BackgroundWorker 类_object_11            this.numericUpDown1 = new System.Windows.Forms.NumericUpDown();

BackgroundWorker 类_object_11            this.startAsyncButton = new System.Windows.Forms.Button();

BackgroundWorker 类_object_11            this.cancelAsyncButton = new System.Windows.Forms.Button();

BackgroundWorker 类_object_11            this.resultLabel = new System.Windows.Forms.Label();

BackgroundWorker 类_object_11            this.progressBar1 = new System.Windows.Forms.ProgressBar();

BackgroundWorker 类_object_11            this.backgroundWorker1 = new System.ComponentModel.BackgroundWorker();

BackgroundWorker 类_object_11            ((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).BeginInit();

BackgroundWorker 类_object_11            this.SuspendLayout();

BackgroundWorker 类_object_11            // 

BackgroundWorker 类_object_11            // numericUpDown1

BackgroundWorker 类_object_11            // 

BackgroundWorker 类_object_11            this.numericUpDown1.Location = new System.Drawing.Point(16, 16);

BackgroundWorker 类_system_12BackgroundWorker 类_object_13            this.numericUpDown1.Maximum = new System.Decimal(new int[] ...{

BackgroundWorker 类_object_11            91,

BackgroundWorker 类_object_11            0,

BackgroundWorker 类_object_11            0,

BackgroundWorker 类_forms_30            0});

BackgroundWorker 类_system_12BackgroundWorker 类_object_13            this.numericUpDown1.Minimum = new System.Decimal(new int[] ...{

BackgroundWorker 类_object_11            1,

BackgroundWorker 类_object_11            0,

BackgroundWorker 类_object_11            0,

BackgroundWorker 类_forms_30            0});

BackgroundWorker 类_object_11            this.numericUpDown1.Name = "numericUpDown1";

BackgroundWorker 类_object_11            this.numericUpDown1.Size = new System.Drawing.Size(80, 20);

BackgroundWorker 类_object_11            this.numericUpDown1.TabIndex = 0;

BackgroundWorker 类_system_12BackgroundWorker 类_object_13            this.numericUpDown1.Value = new System.Decimal(new int[] ...{

BackgroundWorker 类_object_11            1,

BackgroundWorker 类_object_11            0,

BackgroundWorker 类_object_11            0,

BackgroundWorker 类_forms_30            0});

BackgroundWorker 类_object_11            // 

BackgroundWorker 类_object_11            // startAsyncButton

BackgroundWorker 类_object_11            // 

BackgroundWorker 类_object_11            this.startAsyncButton.Location = new System.Drawing.Point(16, 72);

BackgroundWorker 类_object_11            this.startAsyncButton.Name = "startAsyncButton";

BackgroundWorker 类_object_11            this.startAsyncButton.Size = new System.Drawing.Size(120, 23);

BackgroundWorker 类_object_11            this.startAsyncButton.TabIndex = 1;

BackgroundWorker 类_object_11            this.startAsyncButton.Text = "Start Async";

BackgroundWorker 类_object_11            this.startAsyncButton.Click += new System.EventHandler(this.startAsyncButton_Click);

BackgroundWorker 类_object_11            // 

BackgroundWorker 类_object_11            // cancelAsyncButton

BackgroundWorker 类_object_11            // 

BackgroundWorker 类_object_11            this.cancelAsyncButton.Enabled = false;

BackgroundWorker 类_object_11            this.cancelAsyncButton.Location = new System.Drawing.Point(153, 72);

BackgroundWorker 类_object_11            this.cancelAsyncButton.Name = "cancelAsyncButton";

BackgroundWorker 类_object_11            this.cancelAsyncButton.Size = new System.Drawing.Size(119, 23);

BackgroundWorker 类_object_11            this.cancelAsyncButton.TabIndex = 2;

BackgroundWorker 类_object_11            this.cancelAsyncButton.Text = "Cancel Async";

BackgroundWorker 类_object_11            this.cancelAsyncButton.Click += new System.EventHandler(this.cancelAsyncButton_Click);

BackgroundWorker 类_object_11            // 

BackgroundWorker 类_object_11            // resultLabel

BackgroundWorker 类_object_11            // 

BackgroundWorker 类_object_11            this.resultLabel.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;

BackgroundWorker 类_object_11            this.resultLabel.Location = new System.Drawing.Point(112, 16);

BackgroundWorker 类_object_11            this.resultLabel.Name = "resultLabel";

BackgroundWorker 类_object_11            this.resultLabel.Size = new System.Drawing.Size(160, 23);

BackgroundWorker 类_object_11            this.resultLabel.TabIndex = 3;

BackgroundWorker 类_object_11            this.resultLabel.Text = "(no result)";

BackgroundWorker 类_object_11            this.resultLabel.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;

BackgroundWorker 类_object_11            // 

BackgroundWorker 类_object_11            // progressBar1

BackgroundWorker 类_object_11            // 

BackgroundWorker 类_object_11            this.progressBar1.Location = new System.Drawing.Point(18, 48);

BackgroundWorker 类_object_11            this.progressBar1.Name = "progressBar1";

BackgroundWorker 类_object_11            this.progressBar1.Size = new System.Drawing.Size(256, 8);

BackgroundWorker 类_object_11            this.progressBar1.Step = 2;

BackgroundWorker 类_object_11            this.progressBar1.TabIndex = 4;

BackgroundWorker 类_object_11            // 

BackgroundWorker 类_object_11            // backgroundWorker1

BackgroundWorker 类_object_11            // 

BackgroundWorker 类_object_11            this.backgroundWorker1.WorkerReportsProgress = true;

BackgroundWorker 类_object_11            this.backgroundWorker1.WorkerSupportsCancellation = true;

BackgroundWorker 类_object_11            // 

BackgroundWorker 类_object_11            // FibonacciForm

BackgroundWorker 类_object_11            // 

BackgroundWorker 类_object_11            this.ClientSize = new System.Drawing.Size(292, 118);

BackgroundWorker 类_object_11            this.Controls.Add(this.progressBar1);

BackgroundWorker 类_object_11            this.Controls.Add(this.resultLabel);

BackgroundWorker 类_object_11            this.Controls.Add(this.cancelAsyncButton);

BackgroundWorker 类_object_11            this.Controls.Add(this.startAsyncButton);

BackgroundWorker 类_object_11            this.Controls.Add(this.numericUpDown1);

BackgroundWorker 类_object_11            this.Name = "FibonacciForm";

BackgroundWorker 类_object_11            this.Text = "Fibonacci Calculator";

BackgroundWorker 类_object_11            ((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).EndInit();

BackgroundWorker 类_object_11            this.ResumeLayout(false);

BackgroundWorker 类_object_11

BackgroundWorker 类_forms_30        }

BackgroundWorker 类_forms_30        #endregion

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11        [STAThread]

BackgroundWorker 类_object_11        static void Main()

BackgroundWorker 类_system_12BackgroundWorker 类_object_13        ...{

BackgroundWorker 类_object_11            Application.Run(new FibonacciForm());

BackgroundWorker 类_forms_30        }

BackgroundWorker 类_forms_30    }

BackgroundWorker 类_float_319}


C++



BackgroundWorker 类_float#

using   < System.Drawing.dll >

BackgroundWorker 类_float#

using   < System.dll >

BackgroundWorker 类_float#

using   < System.Windows.Forms.dll >

BackgroundWorker 类_float

BackgroundWorker 类_float

using   namespace  System;

BackgroundWorker 类_float

using   namespace  System::Collections;

BackgroundWorker 类_float

using   namespace  System::ComponentModel;

BackgroundWorker 类_float

using   namespace  System::Drawing;

BackgroundWorker 类_float

using   namespace  System::Threading;

BackgroundWorker 类_float

using   namespace  System::Windows::Forms;

BackgroundWorker 类_float

BackgroundWorker 类_float

public   ref   class  FibonacciForm:  public  System::Windows::Forms::Form

BackgroundWorker 类_system_09BackgroundWorker 类_system_10

... {

BackgroundWorker 类_object_11private:

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11   int numberToCompute;

BackgroundWorker 类_object_11   int highestPercentageReached;

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11   System::Windows::Forms::NumericUpDown^ numericUpDown1;

BackgroundWorker 类_object_11   System::Windows::Forms::Button^ startAsyncButton;

BackgroundWorker 类_object_11   System::Windows::Forms::Button^ cancelAsyncButton;

BackgroundWorker 类_object_11   System::Windows::Forms::ProgressBar^ progressBar1;

BackgroundWorker 类_object_11   System::Windows::Forms::Label ^ resultLabel;

BackgroundWorker 类_object_11   System::ComponentModel::BackgroundWorker^ backgroundWorker1;

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11public:

BackgroundWorker 类_object_11   FibonacciForm()

BackgroundWorker 类_system_12BackgroundWorker 类_object_13   ...{

BackgroundWorker 类_object_11      InitializeComponent();

BackgroundWorker 类_object_11      numberToCompute = highestPercentageReached = 0;

BackgroundWorker 类_object_11      InitializeBackgoundWorker();

BackgroundWorker 类_forms_30   }

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11private:

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11   // Set up the BackgroundWorker object by 

BackgroundWorker 类_object_11   // attaching event handlers. 

BackgroundWorker 类_object_11   void InitializeBackgoundWorker()

BackgroundWorker 类_system_12BackgroundWorker 类_object_13   ...{

BackgroundWorker 类_object_11      backgroundWorker1->DoWork += gcnew DoWorkEventHandler( this, &FibonacciForm::backgroundWorker1_DoWork );

BackgroundWorker 类_object_11      backgroundWorker1->RunWorkerCompleted += gcnew RunWorkerCompletedEventHandler( this, &FibonacciForm::backgroundWorker1_RunWorkerCompleted );

BackgroundWorker 类_object_11      backgroundWorker1->ProgressChanged += gcnew ProgressChangedEventHandler( this, &FibonacciForm::backgroundWorker1_ProgressChanged );

BackgroundWorker 类_forms_30   }

BackgroundWorker 类_object_11

BackgroundWorker 类_system_12BackgroundWorker 类_object_13   void startAsyncButton_Click( System::Object^ /**//*sender*/, System::EventArgs^ /**//*e*/ )

BackgroundWorker 类_system_12BackgroundWorker 类_object_13   ...{

BackgroundWorker 类_object_11      

BackgroundWorker 类_object_11      // Reset the text in the result label.

BackgroundWorker 类_object_11      resultLabel->Text = String::Empty;

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11      // Disable the UpDown control until 

BackgroundWorker 类_object_11      // the asynchronous operation is done.

BackgroundWorker 类_object_11      this->numericUpDown1->Enabled = false;

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11      // Disable the Start button until 

BackgroundWorker 类_object_11      // the asynchronous operation is done.

BackgroundWorker 类_object_11      this->startAsyncButton->Enabled = false;

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11      // Enable the Cancel button while 

BackgroundWorker 类_object_11      // the asynchronous operation runs.

BackgroundWorker 类_object_11      this->cancelAsyncButton->Enabled = true;

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11      // Get the value from the UpDown control.

BackgroundWorker 类_object_11      numberToCompute = (int)numericUpDown1->Value;

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11      // Reset the variable for percentage tracking.

BackgroundWorker 类_object_11      highestPercentageReached = 0;

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11      // Start the asynchronous operation.

BackgroundWorker 类_object_11      backgroundWorker1->RunWorkerAsync( numberToCompute );

BackgroundWorker 类_forms_30   }

BackgroundWorker 类_object_11

BackgroundWorker 类_system_12BackgroundWorker 类_object_13   void cancelAsyncButton_Click( System::Object^ /**//*sender*/, System::EventArgs^ /**//*e*/ )

BackgroundWorker 类_system_12BackgroundWorker 类_object_13   ...{  

BackgroundWorker 类_object_11      // Cancel the asynchronous operation.

BackgroundWorker 类_object_11      this->backgroundWorker1->CancelAsync();

BackgroundWorker 类_object_11      

BackgroundWorker 类_object_11      // Disable the Cancel button.

BackgroundWorker 类_object_11      cancelAsyncButton->Enabled = false;

BackgroundWorker 类_forms_30   }

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11   // This event handler is where the actual,

BackgroundWorker 类_object_11   // potentially time-consuming work is done.

BackgroundWorker 类_object_11   void backgroundWorker1_DoWork( Object^ sender, DoWorkEventArgs^ e )

BackgroundWorker 类_system_12BackgroundWorker 类_object_13   ...{

BackgroundWorker 类_object_11      // Get the BackgroundWorker that raised this event.

BackgroundWorker 类_object_11      BackgroundWorker^ worker = dynamic_cast<BackgroundWorker^>(sender);

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11      // Assign the result of the computation

BackgroundWorker 类_object_11      // to the Result property of the DoWorkEventArgs

BackgroundWorker 类_object_11      // object. This is will be available to the 

BackgroundWorker 类_object_11      // RunWorkerCompleted eventhandler.

BackgroundWorker 类_object_11      e->Result = ComputeFibonacci( safe_cast<Int32>(e->Argument), worker, e );

BackgroundWorker 类_forms_30   }

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11   // This event handler deals with the results of the

BackgroundWorker 类_object_11   // background operation.

BackgroundWorker 类_system_12BackgroundWorker 类_object_13   void backgroundWorker1_RunWorkerCompleted( Object^ /**//*sender*/, RunWorkerCompletedEventArgs^ e )

BackgroundWorker 类_system_12BackgroundWorker 类_object_13   ...{

BackgroundWorker 类_object_11      // First, handle the case where an exception was thrown.

BackgroundWorker 类_object_11      if ( e->Error != nullptr )

BackgroundWorker 类_system_12BackgroundWorker 类_object_13      ...{

BackgroundWorker 类_object_11         MessageBox::Show( e->Error->Message );

BackgroundWorker 类_forms_30      }

BackgroundWorker 类_object_11      else

BackgroundWorker 类_object_11      if ( e->Cancelled )

BackgroundWorker 类_system_12BackgroundWorker 类_object_13      ...{

BackgroundWorker 类_object_11         // Next, handle the case where the user cancelled 

BackgroundWorker 类_object_11         // the operation.

BackgroundWorker 类_object_11         // Note that due to a race condition in 

BackgroundWorker 类_object_11         // the DoWork event handler, the Cancelled

BackgroundWorker 类_object_11         // flag may not have been set, even though

BackgroundWorker 类_object_11         // CancelAsync was called.

BackgroundWorker 类_object_11         resultLabel->Text = "Cancelled";

BackgroundWorker 类_forms_30      }

BackgroundWorker 类_object_11      else

BackgroundWorker 类_system_12BackgroundWorker 类_object_13      ...{

BackgroundWorker 类_object_11         // Finally, handle the case where the operation 

BackgroundWorker 类_object_11         // succeeded.

BackgroundWorker 类_object_11         resultLabel->Text = e->Result->ToString();

BackgroundWorker 类_forms_30      }

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11      // Enable the UpDown control.

BackgroundWorker 类_object_11      this->numericUpDown1->Enabled = true;

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11      // Enable the Start button.

BackgroundWorker 类_object_11      startAsyncButton->Enabled = true;

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11      // Disable the Cancel button.

BackgroundWorker 类_object_11      cancelAsyncButton->Enabled = false;

BackgroundWorker 类_forms_30   }

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11   // This event handler updates the progress bar.

BackgroundWorker 类_system_12BackgroundWorker 类_object_13   void backgroundWorker1_ProgressChanged( Object^ /**//*sender*/, ProgressChangedEventArgs^ e )

BackgroundWorker 类_system_12BackgroundWorker 类_object_13   ...{

BackgroundWorker 类_object_11      this->progressBar1->Value = e->ProgressPercentage;

BackgroundWorker 类_forms_30   }

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11   // This is the method that does the actual work. For this

BackgroundWorker 类_object_11   // example, it computes a Fibonacci number and

BackgroundWorker 类_object_11   // reports progress as it does its work.

BackgroundWorker 类_object_11   long ComputeFibonacci( int n, BackgroundWorker^ worker, DoWorkEventArgs ^ e )

BackgroundWorker 类_system_12BackgroundWorker 类_object_13   ...{

BackgroundWorker 类_object_11      // The parameter n must be >= 0 and <= 91.

BackgroundWorker 类_object_11      // Fib(n), with n > 91, overflows a long.

BackgroundWorker 类_object_11      if ( (n < 0) || (n > 91) )

BackgroundWorker 类_system_12BackgroundWorker 类_object_13      ...{

BackgroundWorker 类_object_11         throw gcnew ArgumentException( "value must be >= 0 and <= 91","n" );

BackgroundWorker 类_forms_30      }

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11      long result = 0;

BackgroundWorker 类_object_11      

BackgroundWorker 类_object_11      // Abort the operation if the user has cancelled.

BackgroundWorker 类_object_11      // Note that a call to CancelAsync may have set 

BackgroundWorker 类_object_11      // CancellationPending to true just after the

BackgroundWorker 类_object_11      // last invocation of this method exits, so this 

BackgroundWorker 类_object_11      // code will not have the opportunity to set the 

BackgroundWorker 类_object_11      // DoWorkEventArgs.Cancel flag to true. This means

BackgroundWorker 类_object_11      // that RunWorkerCompletedEventArgs.Cancelled will

BackgroundWorker 类_object_11      // not be set to true in your RunWorkerCompleted

BackgroundWorker 类_object_11      // event handler. This is a race condition.

BackgroundWorker 类_object_11      if ( worker->CancellationPending )

BackgroundWorker 类_system_12BackgroundWorker 类_object_13      ...{

BackgroundWorker 类_object_11         e->Cancel = true;

BackgroundWorker 类_forms_30      }

BackgroundWorker 类_object_11      else

BackgroundWorker 类_system_12BackgroundWorker 类_object_13      ...{

BackgroundWorker 类_object_11         if ( n < 2 )

BackgroundWorker 类_system_12BackgroundWorker 类_object_13         ...{

BackgroundWorker 类_object_11            result = 1;

BackgroundWorker 类_forms_30         }

BackgroundWorker 类_object_11         else

BackgroundWorker 类_system_12BackgroundWorker 类_object_13         ...{

BackgroundWorker 类_object_11            result = ComputeFibonacci( n - 1, worker, e ) + ComputeFibonacci( n - 2, worker, e );

BackgroundWorker 类_forms_30         }

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11         // Report progress as a percentage of the total task.

BackgroundWorker 类_object_11         int percentComplete = (int)((float)n / (float)numberToCompute * 100);

BackgroundWorker 类_object_11         if ( percentComplete > highestPercentageReached )

BackgroundWorker 类_system_12BackgroundWorker 类_object_13         ...{

BackgroundWorker 类_object_11            highestPercentageReached = percentComplete;

BackgroundWorker 类_object_11            worker->ReportProgress( percentComplete );

BackgroundWorker 类_forms_30         }

BackgroundWorker 类_forms_30      }

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11      return result;

BackgroundWorker 类_forms_30   }

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11   void InitializeComponent()

BackgroundWorker 类_system_12BackgroundWorker 类_object_13   ...{

BackgroundWorker 类_object_11      this->numericUpDown1 = gcnew System::Windows::Forms::NumericUpDown;

BackgroundWorker 类_object_11      this->startAsyncButton = gcnew System::Windows::Forms::Button;

BackgroundWorker 类_object_11      this->cancelAsyncButton = gcnew System::Windows::Forms::Button;

BackgroundWorker 类_object_11      this->resultLabel = gcnew System::Windows::Forms::Label;

BackgroundWorker 类_object_11      this->progressBar1 = gcnew System::Windows::Forms::ProgressBar;

BackgroundWorker 类_object_11      this->backgroundWorker1 = gcnew System::ComponentModel::BackgroundWorker;

BackgroundWorker 类_object_11      (dynamic_cast<System::ComponentModel::ISupportInitialize^>(this->numericUpDown1))->BeginInit();

BackgroundWorker 类_object_11      this->SuspendLayout();

BackgroundWorker 类_object_11      

BackgroundWorker 类_object_11      // 

BackgroundWorker 类_object_11      // numericUpDown1

BackgroundWorker 类_object_11      // 

BackgroundWorker 类_object_11      this->numericUpDown1->Location = System::Drawing::Point( 16, 16 );

BackgroundWorker 类_system_12BackgroundWorker 类_object_13      array<Int32>^temp0 = ...{91,0,0,0};

BackgroundWorker 类_object_11      this->numericUpDown1->Maximum = System::Decimal( temp0 );

BackgroundWorker 类_system_12BackgroundWorker 类_object_13      array<Int32>^temp1 = ...{1,0,0,0};

BackgroundWorker 类_object_11      this->numericUpDown1->Minimum = System::Decimal( temp1 );

BackgroundWorker 类_object_11      this->numericUpDown1->Name = "numericUpDown1";

BackgroundWorker 类_object_11      this->numericUpDown1->Size = System::Drawing::Size( 80, 20 );

BackgroundWorker 类_object_11      this->numericUpDown1->TabIndex = 0;

BackgroundWorker 类_system_12BackgroundWorker 类_object_13      array<Int32>^temp2 = ...{1,0,0,0};

BackgroundWorker 类_object_11      this->numericUpDown1->Value = System::Decimal( temp2 );

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11      // 

BackgroundWorker 类_object_11      // startAsyncButton

BackgroundWorker 类_object_11      // 

BackgroundWorker 类_object_11      this->startAsyncButton->Location = System::Drawing::Point( 16, 72 );

BackgroundWorker 类_object_11      this->startAsyncButton->Name = "startAsyncButton";

BackgroundWorker 类_object_11      this->startAsyncButton->Size = System::Drawing::Size( 120, 23 );

BackgroundWorker 类_object_11      this->startAsyncButton->TabIndex = 1;

BackgroundWorker 类_object_11      this->startAsyncButton->Text = "Start Async";

BackgroundWorker 类_object_11      this->startAsyncButton->Click += gcnew System::EventHandler( this, &FibonacciForm::startAsyncButton_Click );

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11      // 

BackgroundWorker 类_object_11      // cancelAsyncButton

BackgroundWorker 类_object_11      // 

BackgroundWorker 类_object_11      this->cancelAsyncButton->Enabled = false;

BackgroundWorker 类_object_11      this->cancelAsyncButton->Location = System::Drawing::Point( 153, 72 );

BackgroundWorker 类_object_11      this->cancelAsyncButton->Name = "cancelAsyncButton";

BackgroundWorker 类_object_11      this->cancelAsyncButton->Size = System::Drawing::Size( 119, 23 );

BackgroundWorker 类_object_11      this->cancelAsyncButton->TabIndex = 2;

BackgroundWorker 类_object_11      this->cancelAsyncButton->Text = "Cancel Async";

BackgroundWorker 类_object_11      this->cancelAsyncButton->Click += gcnew System::EventHandler( this, &FibonacciForm::cancelAsyncButton_Click );

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11      // 

BackgroundWorker 类_object_11      // resultLabel

BackgroundWorker 类_object_11      // 

BackgroundWorker 类_object_11      this->resultLabel->BorderStyle = System::Windows::Forms::BorderStyle::Fixed3D;

BackgroundWorker 类_object_11      this->resultLabel->Location = System::Drawing::Point( 112, 16 );

BackgroundWorker 类_object_11      this->resultLabel->Name = "resultLabel";

BackgroundWorker 类_object_11      this->resultLabel->Size = System::Drawing::Size( 160, 23 );

BackgroundWorker 类_object_11      this->resultLabel->TabIndex = 3;

BackgroundWorker 类_object_11      this->resultLabel->Text = "(no result)";

BackgroundWorker 类_object_11      this->resultLabel->TextAlign = System::Drawing::ContentAlignment::MiddleCenter;

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11      // 

BackgroundWorker 类_object_11      // progressBar1

BackgroundWorker 类_object_11      // 

BackgroundWorker 类_object_11      this->progressBar1->Location = System::Drawing::Point( 18, 48 );

BackgroundWorker 类_object_11      this->progressBar1->Name = "progressBar1";

BackgroundWorker 类_object_11      this->progressBar1->Size = System::Drawing::Size( 256, 8 );

BackgroundWorker 类_object_11      this->progressBar1->Step = 2;

BackgroundWorker 类_object_11      this->progressBar1->TabIndex = 4;

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11      // 

BackgroundWorker 类_object_11      // backgroundWorker1

BackgroundWorker 类_object_11      // 

BackgroundWorker 类_object_11      this->backgroundWorker1->WorkerReportsProgress = true;

BackgroundWorker 类_object_11      this->backgroundWorker1->WorkerSupportsCancellation = true;

BackgroundWorker 类_object_11

BackgroundWorker 类_object_11      // 

BackgroundWorker 类_object_11      // FibonacciForm

BackgroundWorker 类_object_11      // 

BackgroundWorker 类_object_11      this->ClientSize = System::Drawing::Size( 292, 118 );

BackgroundWorker 类_object_11      this->Controls->Add( this->progressBar1 );

BackgroundWorker 类_object_11      this->Controls->Add( this->resultLabel );

BackgroundWorker 类_object_11      this->Controls->Add( this->cancelAsyncButton );

BackgroundWorker 类_object_11      this->Controls->Add( this->startAsyncButton );

BackgroundWorker 类_object_11      this->Controls->Add( this->numericUpDown1 );

BackgroundWorker 类_object_11      this->Name = "FibonacciForm";

BackgroundWorker 类_object_11      this->Text = "Fibonacci Calculator";

BackgroundWorker 类_object_11      (dynamic_cast<System::ComponentModel::ISupportInitialize^>(this->numericUpDown1))->EndInit();

BackgroundWorker 类_object_11      this->ResumeLayout( false );

BackgroundWorker 类_forms_30   }

BackgroundWorker 类_float_319}

;

BackgroundWorker 类_float

BackgroundWorker 类_float[STAThread]

BackgroundWorker 类_float

int  main()

BackgroundWorker 类_system_09BackgroundWorker 类_system_10

... {

BackgroundWorker 类_object_11   Application::Run( gcnew FibonacciForm );

BackgroundWorker 类_float_319}

 继承层次结构

​System.Object​



​System.MarshalByRefObject​



​System.ComponentModel.Component​



System.ComponentModel.BackgroundWorker


 线程安全

此类型的任何公共静态(Visual Basic 中的 ​Shared​)成员都是线程安全的,但不保证所有实例成员都是线程安全的。