zoukankan      html  css  js  c++  java
  • BackgroundWorker——在单独的线程上执行操作

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

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

    若要为后台操作做好准备,请添加 DoWork 事件的事件处理程序。 在此事件处理程序中调用耗时的操作。 若要开始此操作,请调用RunWorkerAsync。 若要收到进度更新的通知,请处理 ProgressChanged 事件。 若要在操作完成时收到通知,请处理 RunWorkerCompleted 事件。

    下面的代码示例演示 BackgroundWorker 类异步执行耗时的基本知识。 下图显示输出的示例。

    BackgroundWorker 简单示例

    using System;
    using System.ComponentModel;
    using System.Windows.Forms;
    
    namespace BackgroundWorkerSimple
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
                backgroundWorker1.WorkerReportsProgress = true;
                backgroundWorker1.WorkerSupportsCancellation = true;
            }
    
            private void startAsyncButton_Click(object sender, EventArgs e)
            {
                if (backgroundWorker1.IsBusy != true)
                {
                    // Start the asynchronous operation.
                    backgroundWorker1.RunWorkerAsync();
                }
            }
    
            private void cancelAsyncButton_Click(object sender, EventArgs e)
            {
                if (backgroundWorker1.WorkerSupportsCancellation == true)
                {
                    // Cancel the asynchronous operation.
                    backgroundWorker1.CancelAsync();
                }
            }
    
            // This event handler is where the time-consuming work is done.
            private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
            {
                BackgroundWorker worker = sender as BackgroundWorker;
    
                for (int i = 1; i <= 10; i++)
                {
                    if (worker.CancellationPending == true)
                    {
                        e.Cancel = true;
                        break;
                    }
                    else
                    {
                        // Perform a time consuming operation and report progress.
                        System.Threading.Thread.Sleep(500);
                        worker.ReportProgress(i * 10);
                    }
                }
            }
    
            // This event handler updates the progress.
            private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
            {
                resultLabel.Text = (e.ProgressPercentage.ToString() + "%");
            }
    
            // This event handler deals with the results of the background operation.
            private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
            {
                if (e.Cancelled == true)
                {
                    resultLabel.Text = "Canceled!";
                }
                else if (e.Error != null)
                {
                    resultLabel.Text = "Error: " + e.Error.Message;
                }
                else
                {
                    resultLabel.Text = "Done!";
                }
            }
        }
    }
    
    注意注意

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

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

    参考文献:微软文档文献

  • 相关阅读:
    [公告] 置顶博客一览
    [公告] 关于花
    【题解】[SNOI2019] 纸牌
    [题解向] PAM简单习题
    [题解向] 带悔贪心泛做
    [题解向] Manacher简单习题
    java记录(2)
    java记录(1)
    js垃圾回收的机制
    盒子的计算
  • 原文地址:https://www.cnblogs.com/zqt14520/p/5848707.html
Copyright © 2011-2022 走看看