博客
关于我
BackgroundWorker类
阅读量:542 次
发布时间:2019-03-08

本文共 5556 字,大约阅读时间需要 18 分钟。

BackgroundWorker类简介

BackgroundWorker类允许在单独的线程上执行耗时操作,避免阻塞用户界面。适用于需要长时间处理任务但不希望影响UI响应的场景。通过事件处理进度和完成状态,实现与UI的交互。
主要功能与使用方法

创建BackgroundWorker实例后,可通过RunWorkerAsync启动任务,DoWork事件处理耗时操作,ProgressChanged事件更新进度,RunWorkerCompleted事件通知完成。支持取消操作,确保线程安全和资源释放。
示例代码

以下示例展示了如何在C#中使用BackgroundWorker类计算斐波那契数:
using System;using System.Collections;using System.ComponentModel;using System.Threading;using System.Windows.Forms; public class FibonacciForm : Form{private int numberToCompute = 0;private int highestPercentageReached = 0;private NumericUpDown numericUpDown1;private Button startAsyncButton;private Button cancelAsyncButton;private ProgressBar progressBar1;private Label resultLabel;private BackgroundWorker backgroundWorker1; public FibonacciForm(){    InitializeComponent();    InitializeBackgroundWorker();}private void InitializeBackgroundWorker(){    backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);    backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);    backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);}private void startAsyncButton_Click(object sender, EventArgs e){    resultLabel.Text = string.Empty;    numericUpDown1.Enabled = false;    startAsyncButton.Enabled = false;    cancelAsyncButton.Enabled = true;    numberToCompute = (int)numericUpDown1.Value;    highestPercentageReached = 0;    backgroundWorker1.RunWorkerAsync(numberToCompute);}private void cancelAsyncButton_Click(object sender, EventArgs e){    backgroundWorker1.CancelAsync();    cancelAsyncButton.Enabled = false;}private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e){    BackgroundWorker worker = sender as BackgroundWorker;    e.Result = ComputeFibonacci((int)e.Argument, worker, e);}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();    }    numericUpDown1.Enabled = true;    startAsyncButton.Enabled = true;    cancelAsyncButton.Enabled = false;}private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e){    progressBar1.Value = e.ProgressPercentage;}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 InitializeComponent(){    numericUpDown1 = new NumericUpDown();    startAsyncButton = new Button();    cancelAsyncButton = new Button();    resultLabel = new Label();    progressBar1 = new ProgressBar();    backgroundWorker1 = new BackgroundWorker();    numericUpDown1.Location = new Point(16, 16);    numericUpDown1.Maximum = new Decimal(new int[] { 91, 0, 0, 0 });    numericUpDown1.Minimum = new Decimal(new int[] { 1, 0, 0, 0 });    numericUpDown1.Name = "numericUpDown1";    numericUpDown1.Size = new Size(80, 20);    numericUpDown1.TabIndex = 0;    numericUpDown1.Value = new Decimal(new int[] { 1, 0, 0, 0 });    startAsyncButton.Location = new Point(16, 72);    startAsyncButton.Name = "startAsyncButton";    startAsyncButton.Size = new Size(120, 23);    startAsyncButton.TabIndex = 1;    startAsyncButton.Text = "Start Async";    startAsyncButton.Click += new EventHandler(startAsyncButton_Click);    cancelAsyncButton.Enabled = false;    cancelAsyncButton.Location = new Point(153, 72);    cancelAsyncButton.Name = "cancelAsyncButton";    cancelAsyncButton.Size = new Size(119, 23);    cancelAsyncButton.TabIndex = 2;    cancelAsyncButton.Text = "Cancel Async";    cancelAsyncButton.Click += new EventHandler(cancelAsyncButton_Click);    resultLabel.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;    resultLabel.Location = new Point(112, 16);    resultLabel.Name = "resultLabel";    resultLabel.Size = new Size(160, 23);    resultLabel.TabIndex = 3;    resultLabel.Text = "(no result)";    resultLabel.TextAlign = ContentAlignment.MiddleCenter;    progressBar1.Location = new Point(18, 48);    progressBar1.Name = "progressBar1";    progressBar1.Size = new Size(256, 8);    progressBar1.Step = 2;    progressBar1.TabIndex = 4;    backgroundWorker1.WorkerReportsProgress = true;    backgroundWorker1.WorkerSupportsCancellation = true;    this.ClientSize = new Size(292, 118);    this.Controls.Add(progressBar1);    this.Controls.Add(resultLabel);    this.Controls.Add(cancelAsyncButton);    this.Controls.Add(startAsyncButton);    this.Controls.Add(numericUpDown1);    this.Name = "FibonacciForm";    this.Text = "Fibonacci Calculator";} }

继承层次结构

BackgroundWorker类继承自System.ComponentModel.Component,支持多种语言绑定。
线程安全

BackgroundWorker类的实例成员在多线程环境中不一定是线程安全的,需谨慎使用。
平台支持

支持Windows 98、Windows 2000 SP4及以上版本的操作系统。
版本信息

.NET Framework 2.0及以上版本支持BackgroundWorker类。
参考文档

获取更多关于BackgroundWorker类的开发文档和资源。

转载地址:http://hytiz.baihongyu.com/

你可能感兴趣的文章
NIFI1.21.0_Mysql到Mysql增量CDC同步中_补充_更新时如果目标表中不存在记录就改为插入数据_Postgresql_Hbase也适用---大数据之Nifi工作笔记0059
查看>>
NIFI1.21.0_NIFI和hadoop蹦了_200G集群磁盘又满了_Jps看不到进程了_Unable to write in /tmp. Aborting----大数据之Nifi工作笔记0052
查看>>
NIFI1.21.0通过Postgresql11的CDC逻辑复制槽实现_指定表多表增量同步_增删改数据分发及删除数据实时同步_通过分页解决变更记录过大问题_02----大数据之Nifi工作笔记0054
查看>>
NIFI1.21.0通过Postgresql11的CDC逻辑复制槽实现_指定表或全表增量同步_实现指定整库同步_或指定数据表同步配置_04---大数据之Nifi工作笔记0056
查看>>
NIFI1.23.2_最新版_性能优化通用_技巧积累_使用NIFI表达式过滤表_随时更新---大数据之Nifi工作笔记0063
查看>>
NIFI从MySql中增量同步数据_通过Mysql的binlog功能_实时同步mysql数据_根据binlog实现数据实时delete同步_实际操作04---大数据之Nifi工作笔记0043
查看>>
NIFI从MySql中增量同步数据_通过Mysql的binlog功能_实时同步mysql数据_配置binlog_使用处理器抓取binlog数据_实际操作01---大数据之Nifi工作笔记0040
查看>>
NIFI从MySql中增量同步数据_通过Mysql的binlog功能_实时同步mysql数据_配置数据路由_实现数据插入数据到目标数据库_实际操作03---大数据之Nifi工作笔记0042
查看>>
NIFI从MySql中增量同步数据_通过Mysql的binlog功能_实时同步mysql数据_配置数据路由_生成插入Sql语句_实际操作02---大数据之Nifi工作笔记0041
查看>>
NIFI从MySql中离线读取数据再导入到MySql中_03_来吧用NIFI实现_数据分页获取功能---大数据之Nifi工作笔记0038
查看>>
NIFI从MySql中离线读取数据再导入到MySql中_无分页功能_02_转换数据_分割数据_提取JSON数据_替换拼接SQL_添加分页---大数据之Nifi工作笔记0037
查看>>
NIFI从PostGresql中离线读取数据再导入到MySql中_带有数据分页获取功能_不带分页不能用_NIFI资料太少了---大数据之Nifi工作笔记0039
查看>>
nifi使用过程-常见问题-以及入门总结---大数据之Nifi工作笔记0012
查看>>
NIFI分页获取Mysql数据_导入到Hbase中_并可通过phoenix客户端查询_含金量很高的一篇_搞了好久_实际操作05---大数据之Nifi工作笔记0045
查看>>
NIFI分页获取Postgresql数据到Hbase中_实际操作---大数据之Nifi工作笔记0049
查看>>
NIFI同步MySql数据_到SqlServer_错误_驱动程序无法通过使用安全套接字层(SSL)加密与SQL Server_Navicat连接SqlServer---大数据之Nifi工作笔记0047
查看>>
Nifi同步过程中报错create_time字段找不到_实际目标表和源表中没有这个字段---大数据之Nifi工作笔记0066
查看>>
NIFI大数据进阶_FlowFile拓扑_对FlowFile内容和属性的修改删除添加_介绍和描述_以及实际操作---大数据之Nifi工作笔记0023
查看>>
NIFI大数据进阶_FlowFile生成器_GenerateFlowFile处理器_ReplaceText处理器_处理器介绍_处理过程说明---大数据之Nifi工作笔记0019
查看>>
NIFI大数据进阶_Json内容转换为Hive支持的文本格式_操作方法说明_01_EvaluteJsonPath处理器---大数据之Nifi工作笔记0031
查看>>