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 ...
随机推荐
- Receiving Transaction Processor Conundrum
what would we do if we are faced with a situation to execute a receiving transaction in oracle ebusi ...
- 博客和Github简单练习
我的第一篇博客 1.首先是自我介绍 姓名:孙弘毅 班级:网工142 学号:1413042050 兴趣:游戏,看书 至于我写了多少代码我也不清楚,反正不多 2.Github 注册流程 (1)百度Git ...
- ERROR 3009 (HY000): Column count of mysql.user is wrong. Expected 45, found 43. Created with MySQL 5
ERROR 3009 (HY000): Column count of mysql.user is wrong. Expected 45, found 43. Created with MySQL 5 ...
- tomcat7-maven-plugin 端口
不知道有没有人像我这样,在pom配置了下面这段之后, <plugins> <plugin> <groupId>org.apache.tomcat.maven< ...
- Postgres 主从配置(五)
PostgreSQL 9.4 新增的一个特性, replication slot, 1. 可以被流复制的sender节点用于自动识别它xlog中的数据在下面的standby中是否还需要(例如, st ...
- Object对象方法 cheet sheet
defineProperty create Object.create(prototype [, propertiesObject ]) prototype:没什么可说的,指定对象的原型 proper ...
- String调用Array相关方法——有点古怪
这个系列的前面几篇文章中有谈到在一个Object上使用apply.call等方法操作另一个Object的方法,今天我们来学习怎么样在String上调用Array相关方法. 在许多方面,字符串表现的好像 ...
- PDF文档转换为图片、图片转成PDF 及PDF合并
简介 功能:PDF文档按每页转换成一张图片,一张图片转换成一张PDF 并将多张PDF合成一个多页的PDF文档. 经历:在各个网站上搜索始终出现各种问题,尤其是遇到引用的版本问题尤其头疼,不是不能适用当 ...
- 基于ASP.NET生成条形码(code128)
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Dr ...
- 创建可复用的自定义 ASP.NET MVC Helpers
通常,在ASP.NET MVC项目中App_Code目录下新建.cshtml编写类似下方的代码就能创建自定义的MVC Helper了, 假设文件名为StrHelper.cshtml,那么在别的视图中的 ...