BackgroundWorker的简单用法

微软的官方例子

BackgroudWorker就是一个封装好的异步处理类(就是多线程,广泛用于winform开发中)

例子:

1.界面效果:

    一个label,两个button

  BackgroundWorker的简单用法

2.Form2.cs的代码

  1 using System;

  2 using System.Collections.Generic;

  3 using System.ComponentModel;

  4 using System.Data;

  5 using System.Drawing;

  6 using System.Linq;

  7 using System.Text;

  8 using System.Windows.Forms;

  9 

 10 namespace BackgroundWorkerTest

 11 {

 12     public partial class Form2 : Form

 13     {

 14         /*

 15          * 使用BackgroundWorker的用法很多

 16          * 1.可以直接从左边控件列表中拖一个到界面中

 17          * 2.动态写代码生成,这里我是把它作为成员变量了

 18          * **/

 19         private BackgroundWorker _worker = new BackgroundWorker();

 20 

 21         public Form2()

 22         {

 23             InitializeComponent();

 24 

 25             //设置是否允许报告进度

 26             _worker.WorkerReportsProgress = true;

 27             //设置是否允许取消

 28             _worker.WorkerSupportsCancellation = true;

 29 

 30 

 31             //BackgroundWorker的三个事件之一,异步处理是所要执行的动作

 32             _worker.DoWork += new DoWorkEventHandler(_worker_DoWork);

 33 

 34             //BackgroundWorker的三个事件之二,当进度改变时所要执行的动作

 35             _worker.ProgressChanged += new ProgressChangedEventHandler(_worker_ProgressChanged);

 36 

 37             //BackgroundWorker的三个事件之三,当任务正常完成或手动取消时,所要执行的动作

 38             _worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(_worker_RunWorkerCompleted);

 39         }

 40 

 41 

 42         //运行RunWorkerAsync()时就出发此方法,而且此方法不能与UI有交互,会抛异常

 43         void _worker_DoWork(object sender, DoWorkEventArgs e)

 44         {

 45             //这个类是用来测试报告进度时,除了可以报告进度外,还可以返回一个object的变量

 46             Person tommy = new Person("Tommy.Huang","25","CXY");

 47 

 48             for (int i = 1; i <= 100; i++)

 49             {

 50                 //如果想要实现能够中途取消的功能,就必须在DoWork里面判断是否点击了取消

 51                 //CancellationPending用于判断是运行了CancelAsync()方法

 52                 if (_worker.CancellationPending)

 53                 {

 54                     e.Cancel = true;

 55                     break;

 56                 }

 57                 else

 58                 {

 59                     _worker.ReportProgress(i,tommy);//ReportProgress可以带1个或2个参数,第一个为进度int,第二个为object

 60                     //因为太快,看不到效果,所以让线程每一次暂停半秒

 61                     System.Threading.Thread.Sleep(100);

 62                 }

 63             }

 64         }

 65 

 66         //当进度有所改变时,就会触发该方法,此方法可以与UI交互,所以通常在此方法中处理

 67         void _worker_ProgressChanged(object sender, ProgressChangedEventArgs e)

 68         {

 69             Person p = e.UserState as Person;

 70             this.label1.Text = e.ProgressPercentage.ToString()+"% -"+p.Name;

 71         }

 72 

 73         //当异步线程正常运行结束,或者点击取消时都会执行此方法

 74         void _worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)

 75         {

 76             if (e.Cancelled)

 77                 System.Windows.Forms.MessageBox.Show("取消了");

 78             else

 79                 System.Windows.Forms.MessageBox.Show("完成了!");

 80         }

 81 

 82         private void btnStart_Click(object sender, EventArgs e)

 83         {

 84             //需要先判断backgroundWorker是否正在运行

 85             if (!_worker.IsBusy)

 86             {

 87                 //RunWorkerAsync()启动线程

 88                 _worker.RunWorkerAsync();

 89             }

 90         }

 91 

 92         private void btnCancel_Click(object sender, EventArgs e)

 93         {

 94             //先判断backgroundWorker是否支持取消

 95             if (_worker.WorkerSupportsCancellation)

 96             {

 97                 //CancelAsync()取消线程

 98                 _worker.CancelAsync();

 99             }

100         }

101 

102     }

103 }
View Code

 

3.控件代码:Form2.Designer.cs

 1 namespace BackgroundWorkerTest

 2 {

 3     partial class Form2

 4     {

 5         /// <summary>

 6         /// Required designer variable.

 7         /// </summary>

 8         private System.ComponentModel.IContainer components = null;

 9 

10         /// <summary>

11         /// Clean up any resources being used.

12         /// </summary>

13         /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>

14         protected override void Dispose(bool disposing)

15         {

16             if (disposing && (components != null))

17             {

18                 components.Dispose();

19             }

20             base.Dispose(disposing);

21         }

22 

23         #region Windows Form Designer generated code

24 

25         /// <summary>

26         /// Required method for Designer support - do not modify

27         /// the contents of this method with the code editor.

28         /// </summary>

29         private void InitializeComponent()

30         {

31             this.btnStart = new System.Windows.Forms.Button();

32             this.btnCancel = new System.Windows.Forms.Button();

33             this.label1 = new System.Windows.Forms.Label();

34             this.SuspendLayout();

35             // 

36             // btnStart

37             // 

38             this.btnStart.Location = new System.Drawing.Point(42, 165);

39             this.btnStart.Name = "btnStart";

40             this.btnStart.Size = new System.Drawing.Size(75, 23);

41             this.btnStart.TabIndex = 0;

42             this.btnStart.Text = "开始";

43             this.btnStart.UseVisualStyleBackColor = true;

44             this.btnStart.Click += new System.EventHandler(this.btnStart_Click);

45             // 

46             // btnCancel

47             // 

48             this.btnCancel.Location = new System.Drawing.Point(249, 165);

49             this.btnCancel.Name = "btnCancel";

50             this.btnCancel.Size = new System.Drawing.Size(75, 23);

51             this.btnCancel.TabIndex = 1;

52             this.btnCancel.Text = "取消";

53             this.btnCancel.UseVisualStyleBackColor = true;

54             this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);

55             // 

56             // label1

57             // 

58             this.label1.AutoSize = true;

59             this.label1.Location = new System.Drawing.Point(61, 47);

60             this.label1.Name = "label1";

61             this.label1.Size = new System.Drawing.Size(35, 13);

62             this.label1.TabIndex = 2;

63             this.label1.Text = "label1";

64             // 

65             // Form2

66             // 

67             this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);

68             this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;

69             this.ClientSize = new System.Drawing.Size(388, 230);

70             this.Controls.Add(this.label1);

71             this.Controls.Add(this.btnCancel);

72             this.Controls.Add(this.btnStart);

73             this.Name = "Form2";

74             this.Text = "Form2";

75             this.ResumeLayout(false);

76             this.PerformLayout();

77 

78         }

79 

80         #endregion

81 

82         private System.Windows.Forms.Button btnStart;

83         private System.Windows.Forms.Button btnCancel;

84         private System.Windows.Forms.Label label1;

85     }

86 }
View Code

 

你可能感兴趣的:(background)