zoukankan      html  css  js  c++  java
  • backgroundWorker1

    为了确保 backgroundWorker1_ProgressChanged事件能起作用 设置 WorkerReportsProgress = True;

    为了确保能取消操作 设置 WorkerSupportsCancellation = True  这样代码 backgroundWorker1.CancelAsync(); 就不会出错


    clipboard

    clipboard



    using System;
    using System.ComponentModel;
    using System.Threading;
    using System.Windows.Forms;
    
    namespace WindowsFormsAppBackGroundWorker {
        public partial class Form1 : Form {
            public Form1() {
                InitializeComponent();
            }
    
            private void button1_Click(object sender,EventArgs e) {
                //start
                if (!backgroundWorker1.IsBusy)
                    backgroundWorker1.RunWorkerAsync(textBox1.Text);

                   //此处的Object数值 存放在 DoWorkEventArgs的Argument里面
                    //可在 backgroundWorker1_DoWork事件的  e.Argument获取

            }
    
    
            private void button2_Click(object sender,EventArgs e) {
                //stop
                //backgroundWorker1.WorkerSupportsCancellation = true;
                if (backgroundWorker1.IsBusy)
                    backgroundWorker1.CancelAsync();
            }
    
    
            private void backgroundWorker1_DoWork(object sender,DoWorkEventArgs e) {
    
                int length = int.Parse(textBox1.Text);
                progressBar1.Maximum = length;
    
                backgroundWorker1.ReportProgress(1,"Begin...");
    
                for (int i = 0; i < length; i++) {
                    if (!backgroundWorker1.CancellationPending) {
                        backgroundWorker1.ReportProgress(i,i);
                        Thread.Sleep(10);
                    }
                }
    
                backgroundWorker1.ReportProgress(100,"Complete!");
            }
    
            private void backgroundWorker1_ProgressChanged(object sender,ProgressChangedEventArgs e) {
                 progressBar1.Value = unchecked(e.ProgressPercentage);
                 label1.Text = e.UserState.ToString();
            }
    
            private void backgroundWorker1_RunWorkerCompleted(object sender,RunWorkerCompletedEventArgs e) {
                //Text = "RunWorkerCompleted";
            }
         }
    }
    
  • 相关阅读:
    Webdriver启动Firefox浏览器后,页面显示空白
    Windows+Python+Selenium基础篇之1-环境搭建
    office2010无法卸载问题
    .NET使用FastDBF读写DBF
    并发编程相关概念
    C#的多线程简洁笔记
    asp.net core 3.1 入口:Program.cs中的Main函数
    【WPF学习】第四十四章 图画
    .NET知识梳理——1.泛型Generic
    C#个推SDK推送安卓+iOS
  • 原文地址:https://www.cnblogs.com/xe2011/p/13194684.html
Copyright © 2011-2022 走看看