• 多线程BackgroundWorker


    链接: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(2785);
                
    this.progressBar1.Name = "progressBar1";
                
    this.progressBar1.Size = new System.Drawing.Size(21823);
                
    this.progressBar1.TabIndex = 0;
                
    // 
                
    // button1
                
    // 
                this.button1.Location = new System.Drawing.Point(12222);
                
    this.button1.Name = "button1";
                
    this.button1.Size = new System.Drawing.Size(5423);
                
    this.button1.TabIndex = 1;
                
    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(72222);
                
    this.button2.Name = "button2";
                
    this.button2.Size = new System.Drawing.Size(5323);
                
    this.button2.TabIndex = 2;
                
    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(131222);
                
    this.button3.Name = "button3";
                
    this.button3.Size = new System.Drawing.Size(5723);
                
    this.button3.TabIndex = 3;
                
    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(145124);
                
    this.textBox2.Name = "textBox2";
                
    this.textBox2.Size = new System.Drawing.Size(10020);
                
    this.textBox2.TabIndex = 5;
                
    // 
                
    // 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(33175);
                
    this.label3.Name = "label3";
                
    this.label3.Size = new System.Drawing.Size(5413);
                
    this.label3.TabIndex = 6;
                
    this.label3.Text = "UserState";
                
    // 
                
    // label1
                
    // 
                this.label1.AutoSize = true;
                
    this.label1.Location = new System.Drawing.Point(24127);
                
    this.label1.Name = "label1";
                
    this.label1.Size = new System.Drawing.Size(10913);
                
    this.label1.TabIndex = 7;
                
    this.label1.Text = "Please input  number:";
                
    // 
                
    // button4
                
    // 
                this.button4.Location = new System.Drawing.Point(194222);
                
    this.button4.Name = "button4";
                
    this.button4.Size = new System.Drawing.Size(6123);
                
    this.button4.TabIndex = 8;
                
    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(292273);
                
    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 = 0;
            
    int j = 0;
            
    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 = 0; i < num; i++)
                    
    {
                        
    if (!worker.CancellationPending)
                        
    {
                            j 
    = i;
                            Thread.Sleep(
    100);
                            worker.ReportProgress(i 
    * 100 / num, i);
                            
    if (backgroundWorker1.CancellationPending)
                            
    {

                                e.Cancel 
    = true;

                                
    break;
                            }


                        }

                    }

                }

                
    else
                
    {
                    
    for (i = j; i < num; i++)
                    
    {
                        
    if (!worker.CancellationPending)
                        
    {
                            j 
    = i;
                            Thread.Sleep(
    100);
                            worker.ReportProgress(i 
    * 100 / 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 = 0;
                f 
    = false;
                
    this.label3.Text = "";
                
    this.textBox2.Text = "";
                
            }



        }

    }
  • 相关阅读:
    JDBC性能优化点
    56992 vuser_init.c(12): Error: Socket descriptor not found.
    ubuntu用apt安装apache2时,出现E:未发现软件包 apache2
    loadrunner --global schedule设置
    loadrunner ---模拟多IP登录
    Loadrunner ---集合点设置
    LoadRunner --HTML/URL录制方式的选择规则
    LoadRunner ---参数化数据源(oracle,mssql,excel)
    LoadRunner ---协议分析
    LoadRunner ---思考时间设置
  • 原文地址:https://www.cnblogs.com/xcsn/p/3171398.html
Copyright © 2020-2023  润新知