BackgroundWorker的简单用法
BackgroudWorker就是一个封装好的异步处理类(就是多线程,广泛用于winform开发中)
例子:
1.界面效果:
一个label,两个button

2.Form2.cs的代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms; namespace BackgroundWorkerTest
{
public partial class Form2 : Form
{
/*
* 使用BackgroundWorker的用法很多
* 1.可以直接从左边控件列表中拖一个到界面中
* 2.动态写代码生成,这里我是把它作为成员变量了
* **/
private BackgroundWorker _worker = new BackgroundWorker(); public Form2()
{
InitializeComponent(); //设置是否允许报告进度
_worker.WorkerReportsProgress = true;
//设置是否允许取消
_worker.WorkerSupportsCancellation = true; //BackgroundWorker的三个事件之一,异步处理是所要执行的动作
_worker.DoWork += new DoWorkEventHandler(_worker_DoWork); //BackgroundWorker的三个事件之二,当进度改变时所要执行的动作
_worker.ProgressChanged += new ProgressChangedEventHandler(_worker_ProgressChanged); //BackgroundWorker的三个事件之三,当任务正常完成或手动取消时,所要执行的动作
_worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(_worker_RunWorkerCompleted);
} //运行RunWorkerAsync()时就出发此方法,而且此方法不能与UI有交互,会抛异常
void _worker_DoWork(object sender, DoWorkEventArgs e)
{
//这个类是用来测试报告进度时,除了可以报告进度外,还可以返回一个object的变量
Person tommy = new Person("Tommy.Huang","","CXY"); for (int i = ; i <= ; i++)
{
//如果想要实现能够中途取消的功能,就必须在DoWork里面判断是否点击了取消
//CancellationPending用于判断是运行了CancelAsync()方法
if (_worker.CancellationPending)
{
e.Cancel = true;
break;
}
else
{
_worker.ReportProgress(i,tommy);//ReportProgress可以带1个或2个参数,第一个为进度int,第二个为object
//因为太快,看不到效果,所以让线程每一次暂停半秒
System.Threading.Thread.Sleep();
}
}
} //当进度有所改变时,就会触发该方法,此方法可以与UI交互,所以通常在此方法中处理
void _worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
Person p = e.UserState as Person;
this.label1.Text = e.ProgressPercentage.ToString()+"% -"+p.Name;
} //当异步线程正常运行结束,或者点击取消时都会执行此方法
void _worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
System.Windows.Forms.MessageBox.Show("取消了");
else
System.Windows.Forms.MessageBox.Show("完成了!");
} private void btnStart_Click(object sender, EventArgs e)
{
//需要先判断backgroundWorker是否正在运行
if (!_worker.IsBusy)
{
//RunWorkerAsync()启动线程
_worker.RunWorkerAsync();
}
} private void btnCancel_Click(object sender, EventArgs e)
{
//先判断backgroundWorker是否支持取消
if (_worker.WorkerSupportsCancellation)
{
//CancelAsync()取消线程
_worker.CancelAsync();
}
} }
}
3.控件代码:Form2.Designer.cs
namespace BackgroundWorkerTest
{
partial class Form2
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null; /// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
} #region Windows Form Designer generated code /// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.btnStart = new System.Windows.Forms.Button();
this.btnCancel = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// btnStart
//
this.btnStart.Location = new System.Drawing.Point(, );
this.btnStart.Name = "btnStart";
this.btnStart.Size = new System.Drawing.Size(, );
this.btnStart.TabIndex = ;
this.btnStart.Text = "开始";
this.btnStart.UseVisualStyleBackColor = true;
this.btnStart.Click += new System.EventHandler(this.btnStart_Click);
//
// btnCancel
//
this.btnCancel.Location = new System.Drawing.Point(, );
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size(, );
this.btnCancel.TabIndex = ;
this.btnCancel.Text = "取消";
this.btnCancel.UseVisualStyleBackColor = true;
this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(, );
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(, );
this.label1.TabIndex = ;
this.label1.Text = "label1";
//
// Form2
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(, );
this.Controls.Add(this.label1);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.btnStart);
this.Name = "Form2";
this.Text = "Form2";
this.ResumeLayout(false);
this.PerformLayout(); } #endregion private System.Windows.Forms.Button btnStart;
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.Label label1;
}
}
BackgroundWorker的简单用法的更多相关文章
- CATransition(os开发之画面切换) 的简单用法
CATransition 的简单用法 //引进CATransition 时要添加包“QuartzCore.framework”,然后引进“#import <QuartzCore/QuartzCo ...
- jquery.validate.js 表单验证简单用法
引入jquery.validate.js插件以及Jquery,在最后加上这个插件的方法名来引用.$('form').validate(); <!DOCTYPE html PUBLIC " ...
- NSCharacterSet 简单用法
NSCharacterSet 简单用法 NSCharacterSet其实是许多字符或者数字或者符号的组合,在网络处理的时候会用到 NSMutableCharacterSet *base = [NSMu ...
- [转]Valgrind简单用法
[转]Valgrind简单用法 http://www.cnblogs.com/sunyubo/archive/2010/05/05/2282170.html Valgrind的主要作者Julian S ...
- Oracle的substr函数简单用法
substr(字符串,截取开始位置,截取长度) //返回截取的字 substr('Hello World',0,1) //返回结果为 'H' *从字符串第一个字符开始截取长度为1的字符串 subst ...
- Ext.Net学习笔记19:Ext.Net FormPanel 简单用法
Ext.Net学习笔记19:Ext.Net FormPanel 简单用法 FormPanel是一个常用的控件,Ext.Net中的FormPanel控件同样具有非常丰富的功能,在接下来的笔记中我们将一起 ...
- TransactionScope简单用法
记录TransactionScope简单用法,示例如下: void Test() { using (TransactionScope scope = new TransactionScope()) { ...
- WPF之Treeview控件简单用法
TreeView:表示显示在树结构中分层数据具有项目可展开和折叠的控件 TreeView 的内容是可以包含丰富内容的 TreeViewItem 控件,如 Button 和 Image 控件.TreeV ...
- listActivity和ExpandableListActivity的简单用法
http://www.cnblogs.com/limingblogs/archive/2011/10/09/2204866.html 今天自己简单的总结了listActivity和Expandable ...
随机推荐
- FMX.Platform.TApplicationEvent
FMX.Platform.TApplicationEvent http://docwiki.embarcadero.com/Libraries/Seattle/en/FMX.Platform.TApp ...
- 咏南 DATASNAP LINUX中间件
咏南 DATASNAP LINUX中间件,一套源码,同时支持WINDOWS和LINUX操作系统. 基于DELPHI 10.2 TOKYO开发 使用FIREDAC数据库引擎,支持MYSQL,MSSQL, ...
- Android-openFileInput openFileOutput
Android设计了一套可以操作自身APP目录文件对API openFileInput openFileOutput,读取只需传入文件名,写入需要传入文件名 与 权限模式 界面: 布局代码: < ...
- CentOS 系统状况查看
1 磁盘 iostat 安装 yum install sysstat iostat -x Linux -.el7.x86_64 (sdw2) 2017年03月07日 _x86_64_ ( CPU ...
- 存储系统的基本数据结构之一: 跳表 (SkipList)
在接下来的系列文章中,我们将介绍一系列应用于存储以及IO子系统的数据结构.这些数据结构相互关联又有着巨大的区别,希望我们能够不辱使命的将他们分门别类的介绍清楚.本文为第一节,介绍一个简单而又有用的数据 ...
- 【OCP-12c】2019年CUUG OCP 071考试题库(75题)
75.Which statements are correct regarding indexes? (Choose all that apply.) A. A non-deferrable PRIM ...
- js滚动距离
滚动距离 onclick="$('html,body').animate({scrollTop:$('.J_user_evaluate').offset().top-110},500)&qu ...
- MongoDB 数据自动同步到 ElasticSearch
我们产品中需要全文检索的功能,后端数据存储主要使用了 MySQL + MongoDB,而其中需要检索的内容是在 MongoDB 中的. MongoDB 本身是自带文本索引功能的,但是,不支持中文.术业 ...
- var 是 Java 开发的好朋友啊!
简评:Java var != JavaScript var. Java 10 中引入了新的语法用于局部变量类型推断,很多开发者有所疑惑,希望这篇文章能帮到你. 什么是类型推断 其实在 Java 中类型 ...
- javascript获取wx.config内部字段解决微信分享
转自:http://www.jb51.net/article/80679.htm 专题推荐:js微信开发_脚本之家 http://www.jb51.net/Special/879.htm 背景在微信分 ...