链接:http://www.cnblogs.com/yiyisawa/archive/2008/11/24/1339826.html

周六闲来无事,学习了多线程BackgroundWorker,以此记录。

此案例功能:

实现用BackgroundWorker处理进度条,可以开始,暂停,继续,清空。

BackgroundWorker说明:   摘抄自---http://msdn.microsoft.com

BackgroundWorker 类允许您在单独的专用线程上运行操作。耗时的操作(如下载和数据库事务)在长时间运行时可能会导致用户界面 (UI) 似乎处于停止响应状态。如果您需要能进行响应的用户界面,而且面临与这类操作相关的长时间延迟,则可以使用 BackgroundWorker 类方便地解决问题。若要在后台执行耗时的操作,请创建一个 BackgroundWorker,侦听那些报告操作进度并在操作完成时发出信号的事件。可以通过编程方式创建 BackgroundWorker,也可以将它从“工具箱”的“组件”选项卡中拖到窗体上。如果在 Windows 窗体设计器中创建 BackgroundWorker,则它会出现在组件栏中,而且它的属性会显示在“属性”窗口中。若要设置后台操作,请为 DoWork 事件添加一个事件处理程序。在此事件处理程序中调用耗时的操作。若要启动该操作,请调用 RunWorkerAsync。若要收到进度更新通知,请对 ProgressChanged 事件进行处理。若要在操作完成时收到通知,请对 RunWorkerCompleted 事件进行处理。

您必须非常小心,确保在 DoWork 事件处理程序中不操作任何用户界面对象。而应该通过 ProgressChanged 和 RunWorkerCompleted 事件与用户界面进行通信。

BackgroundWorker 事件不跨 AppDomain 边界进行封送处理。请不要使用 BackgroundWorker 组件在多个 AppDomain 中执行多线程操作。如果后台操作需要参数,请在调用 RunWorkerAsync 时给出参数。在 DoWork 事件处理程序内部,可以从 DoWorkEventArgs..::.Argument 属性中提取该参数。


namespace WindowsApplication1

{

    partial class Form1

    {

        /// <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.colorDialog1 = new System.Windows.Forms.ColorDialog();

            this.colorDialog2 = new System.Windows.Forms.ColorDialog();

            this.progressBar1 = new System.Windows.Forms.ProgressBar();

            this.button1 = new System.Windows.Forms.Button();

            this.button2 = new System.Windows.Forms.Button();

            this.button3 = new System.Windows.Forms.Button();

            this.textBox2 = new System.Windows.Forms.TextBox();

            this.backgroundWorker1 = new System.ComponentModel.BackgroundWorker();

            this.label3 = new System.Windows.Forms.Label();

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

            this.button4 = new System.Windows.Forms.Button();

            this.SuspendLayout();

            // 

            // progressBar1

            // 

            this.progressBar1.Location = new System.Drawing.Point(, );

            this.progressBar1.Name = "progressBar1";

            this.progressBar1.Size = new System.Drawing.Size(, );

            this.progressBar1.TabIndex = ;

            // 

            // button1

            // 

            this.button1.Location = new System.Drawing.Point(, );

            this.button1.Name = "button1";

            this.button1.Size = new System.Drawing.Size(, );

            this.button1.TabIndex = ;

            this.button1.Text = "Execute ";

            this.button1.UseVisualStyleBackColor = true;

            this.button1.Click += new System.EventHandler(this.button1_Click);

            // 

            // button2

            // 

            this.button2.Location = new System.Drawing.Point(, );

            this.button2.Name = "button2";

            this.button2.Size = new System.Drawing.Size(, );

            this.button2.TabIndex = ;

            this.button2.Text = "Cancel";

            this.button2.UseVisualStyleBackColor = true;

            this.button2.Click += new System.EventHandler(this.button2_Click);

            // 

            // button3

            // 

            this.button3.Location = new System.Drawing.Point(, );

            this.button3.Name = "button3";

            this.button3.Size = new System.Drawing.Size(, );

            this.button3.TabIndex = ;

            this.button3.Text = "Continue ";

            this.button3.UseVisualStyleBackColor = true;

            this.button3.Click += new System.EventHandler(this.button3_Click);

            // 

            // textBox2

            // 

            this.textBox2.Location = new System.Drawing.Point(, );

            this.textBox2.Name = "textBox2";

            this.textBox2.Size = new System.Drawing.Size(, );

            this.textBox2.TabIndex = ;

            // 

            // backgroundWorker1

            // 

            this.backgroundWorker1.WorkerReportsProgress = true;

            this.backgroundWorker1.WorkerSupportsCancellation = true;

            this.backgroundWorker1.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker1_DoWork);

            this.backgroundWorker1.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorker1_RunWorkerCompleted);

            this.backgroundWorker1.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.backgroundWorker1_ProgressChanged);

            // 

            // label3

            // 

            this.label3.AutoSize = true;

            this.label3.Location = new System.Drawing.Point(, );

            this.label3.Name = "label3";

            this.label3.Size = new System.Drawing.Size(, );

            this.label3.TabIndex = ;

            this.label3.Text = "UserState";

            // 

            // 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 = "Please input  number:";

            // 

            // button4

            // 

            this.button4.Location = new System.Drawing.Point(, );

            this.button4.Name = "button4";

            this.button4.Size = new System.Drawing.Size(, );

            this.button4.TabIndex = ;

            this.button4.Text = "Clear";

            this.button4.UseVisualStyleBackColor = true;

            this.button4.Click += new System.EventHandler(this.button4_Click);

            // 

            // Form1

            // 

            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.button4);

            this.Controls.Add(this.label1);

            this.Controls.Add(this.label3);

            this.Controls.Add(this.textBox2);

            this.Controls.Add(this.button3);

            this.Controls.Add(this.button2);

            this.Controls.Add(this.button1);

            this.Controls.Add(this.progressBar1);

            this.Name = "Form1";

            this.Text = "Form1";

            this.ResumeLayout(false);

            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.ColorDialog colorDialog1;

        private System.Windows.Forms.ColorDialog colorDialog2;

        private System.Windows.Forms.ProgressBar progressBar1;

        private System.Windows.Forms.Button button1;

        private System.Windows.Forms.Button button2;

        private System.Windows.Forms.Button button3;

        private System.Windows.Forms.TextBox textBox2;

        private System.ComponentModel.BackgroundWorker backgroundWorker1;

        private System.Windows.Forms.Label label3;

        private System.Windows.Forms.Label label1;

        private System.Windows.Forms.Button button4;

    }

}

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.Threading;

using System.Net;

namespace WindowsApplication1

{

    public partial class Form1 : Form

    {

        //加载窗体

        public Form1()

        {

            InitializeComponent();

        }

        #region define

        int i = ;

        int j = ;

        bool f = false;

        #endregion

      

        private void button1_Click(object sender, EventArgs e)

        {

            backgroundWorker1.RunWorkerAsync();

        }

        //按钮单击事件启动后台线程DoWok事件

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)

        {

            BackgroundWorker worker = (BackgroundWorker)sender;

            int num = int.Parse(textBox2.Text);

            if (f == false)

            {

                for (i = ; i < num; i++)

                {

                    if (!worker.CancellationPending)

                    {

                        j = i;

                        Thread.Sleep();

                        worker.ReportProgress(i *  / num, i);

                        if (backgroundWorker1.CancellationPending)

                        {

                            e.Cancel = true;

                            break;

                        }

                    }

                }

            }

            else

            {

                for (i = j; i < num; i++)

                {

                    if (!worker.CancellationPending)

                    {

                        j = i;

                        Thread.Sleep();

                        worker.ReportProgress(i *  / num, i);

                        if (backgroundWorker1.CancellationPending)

                        {

                            e.Cancel = true;

                            break;

                        }

                    }

                }

            }

            

        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)

        {

            progressBar1.Value = e.ProgressPercentage;

            label3.Text = e.UserState.ToString();

        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)

        {

            if (e.Cancelled)

            {

                label3.Text = "已经取消!";

            }

            else

            {

                MessageBox.Show("ok");

            }

        }

        private void button2_Click(object sender, EventArgs e)

        {

            backgroundWorker1.CancelAsync();

           

            label3.Text = "正在取消。。";

        }

        private void button3_Click(object sender, EventArgs e)

        {

            f = true;

            backgroundWorker1.RunWorkerAsync();

        }

        private void button4_Click(object sender, EventArgs e)

        {

            backgroundWorker1.CancelAsync();

         

            this.progressBar1.Value = ;

            f = false;

            this.label3.Text = "";

            this.textBox2.Text = "";

            

        }

    }

}

多线程BackgroundWorker的更多相关文章

  1. WPF 分页控件 WPF 多线程 BackgroundWorker

    WPF 分页控件 WPF 多线程 BackgroundWorker 大家好,好久没有发表一篇像样的博客了,最近的开发实在头疼,很多东西无从下口,需求没完没了,更要命的是公司的开发从来不走正规流程啊, ...

  2. 让你的WPF程序使用多线程——BackgroundWorker

    在wpf中可以使用许多方法执行异步操作.利用.NET的芳芳就是手动创建一个新的System.Threading.Thread对象,提供一步代码,并使用THread.Start()方法加载代码.这种方法 ...

  3. 解析大型.NET ERP系统 高质量.NET代码设计模式

    1 缓存 Cache 系统中大量的用到缓存设计模式,对系统登入之后不变的数据进行缓存,不从数据库中直接读取.耗费一些内存,相比从SQL Server中再次读取数据要划算得多.缓存的基本设计模式参考下面 ...

  4. c# BackGroundWorker 多线程操作的小例子

    在我们的程序中,经常会有一些耗时较长的运算,为了保证用户体验,不引起界面不响应,我们一般会采用多线程操作,让耗时操作在后台完成,完成后再进行处理或给出提示,在运行中,也会时时去刷新界面上的进度条等显示 ...

  5. 1、简单的BackGroundWorker多线程时时刷新UI界面,并显示进度

    BackGroundWorker是微软提供的封装好了的,非常实用的控件,我们可以在控件中将其拖到Winform之中,然后简单的系统生成代码式的编辑事件处理. 以下是,比较经典且简单的实用,后面的一篇较 ...

  6. 【WPF/C#】使用BackgroundWorker实现多线程/异步操作

    做WPF时需要做一个异步加载时的Loading遮罩,搜Stackoverflow看到很多方法,看到了这个插件: BusyIndicator in the extended WPF Toolkit 同时 ...

  7. c# BackGroundWorker 多线程操作的小例子 (转)

    在我们的程序中,经常会有一些耗时较长的运算,为了保证用户体验,不引起界面不响应,我们一般会采用多线程操作,让耗时操作在后台完成,完成后再进行处理或给出提示,在运行中,也会时时去刷新界面上的进度条等显示 ...

  8. 在UI程序设计中使用BackgroundWorker进行多线程异步处

    WinForm的应用程序中如果执行了一个的非常冗长的处理操作,(比如文件检索,大运算量计算),在执行时就会锁定用户界面,虽然主活动窗口还在运行,但用户无法与程序交互,无法移动窗体或改变窗体大小,导致程 ...

  9. BackgroundWorker+ProgressBar+委托 实现多线程、进度条

    上文在<C# 使用BackgroundWorker实现WinForm异步>介绍了如何通过BackgroundWorker实现winForm异步通信,下面介绍如何通过BackgroundWo ...

随机推荐

  1. OC中几种集合的遍历方法(数组遍历,字典遍历,集合遍历)

    // 先分别初始化数组.字典和集合,然后分别用for循环.NSEnumerator枚举器和forin循环这三个方法来实现遍历 NSArray *array = @[@"yinhao" ...

  2. MySQL 强制操作以及order by 使用

    我们以MySQL中常用的hint来进行详细的解析,如果你是经常使用Oracle的朋友可能知道,Oracle的hincvt功能种类很多,对于优化sql语句提供了很多方法. 同样,在MySQL里,也有类似 ...

  3. 在Asp.net MVC中使用Authorization Manager (AzMan)进行Windows用户身份认证

    背景 创建需要通过Windows用户进行身份认证的Asp.net MVC应用 要点 在Asp.net MVC应用基于Windows用户进行身份认证的方法有很多,如MVC自带的Windows认证就经常被 ...

  4. apt-get报错could not get lock /var/lib/dpkg/lock -open等

    用apt-get命令安装一些软件包时,总报错:E:could not get lock /var/lib/dpkg/lock -open等 出现这个问题的原因可能是有另外一个程序正在运行,导致资源被锁 ...

  5. SQL Server 2008 R2——VC++ ADO 操作 存储过程

    ==================================声明================================== 本文原创,转载在正文中显要的注明作者和出处,并保证文章的完 ...

  6. jQuery Form 表单提交插件----Form 简介,官方文档,官方下载地址

     一.jQuery Form简介 jQuery Form插件是一个优秀的Ajax表单插件,可以非常容易地.无侵入地升级HTML表单以支持Ajax.jQuery Form有两个核心方法 -- ajaxF ...

  7. jQuery实现联动下拉列表查询框

    <!DOCTaYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org ...

  8. 升级了win10后开启wifi热点出现iphone&macbook连接断线的问题(win7也一样)

    升级了win10后开启wifi热点出现iphone&macbook连接 不间断 断线的问题 文后附上开启虚拟wifi的办法 百度参考了别人也出现这种问题,解决办法是修改信道,默认信道是11,修 ...

  9. java自带命令工具

    jstat,这个工具很强大,可以监测Java虚拟机GC多方面的状态,具体参数含义参见此链接: ./jstat -gc 84012 1000 3 S0C    S1C    S0U    S1U     ...

  10. 如何在WIN7下进行LINUX虚拟机搭建

    Linux是一套免费使用和自由传播的类Unix操作系统,非常适用于搭建网络服务器等,我本人日常工作时,是使用的LINUX和WIN7双操作系统,但每次更换系统总要关机重启很不方便,所以也在WIN7下搭建 ...