博客
关于我
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/

你可能感兴趣的文章
nginx+uwsgi+django
查看>>
Nginx-http-flv-module流媒体服务器搭建+模拟推流+flv.js在前端html和Vue中播放HTTP-FLV视频流
查看>>
nginx-vts + prometheus 监控nginx
查看>>
Nginx下配置codeigniter框架方法
查看>>
Nginx之二:nginx.conf简单配置(参数详解)
查看>>
Nginx代理websocket配置(解决websocket异常断开连接tcp连接不断问题)
查看>>
Nginx代理初探
查看>>
nginx代理地图服务--离线部署地图服务(地图数据篇.4)
查看>>
Nginx代理外网映射
查看>>
Nginx代理模式下 log-format 获取客户端真实IP
查看>>
Nginx代理解决跨域问题(导致图片只能预览不能下载)
查看>>
Nginx代理配置详解
查看>>
Nginx代理静态资源(gis瓦片图片)实现非固定ip的url适配网络环境映射ip下的资源请求解决方案
查看>>
Nginx代理静态资源(gis瓦片图片)实现非固定ip的url适配网络环境映射ip下的资源请求解决方案
查看>>
nginx反向代理
查看>>
nginx反向代理、文件批量改名及统计ip访问量等精髓总结
查看>>
Nginx反向代理与正向代理配置
查看>>
Nginx反向代理及负载均衡实现过程部署
查看>>
Nginx反向代理是什么意思?如何配置Nginx反向代理?
查看>>
nginx反向代理解决跨域问题,使本地调试更方便
查看>>