zoukankan      html  css  js  c++  java
  • c# BackgroundWorker初试

    /*
     * Created by SharpDevelop.
     * User: Administrator
     * Date: 2017/7/31
     * Time: 16:18
     * 
     * To change this template use Tools | Options | Coding | Edit Standard Headers.
     */
    using System;
    using System.Collections.Generic;
    using System.Drawing;
    using System.Windows.Forms;
    using System.Threading;
    using System.ComponentModel;
    
    namespace App
    {
        /// <summary>
        /// Description of MainForm.
        /// </summary>
        public partial class MainForm : Form
        {
            private BackgroundWorker bw;
            public MainForm()
            {
                //
                // The InitializeComponent() call is required for Windows Forms designer support.
                //
                InitializeComponent();
    
                //
                // TODO: Add constructor code after the InitializeComponent() call.
                //
            }
            void process1_Exited(object sender, EventArgs e)
            {
                // TODO: Implement process1_Exited
            }
    
            private void MainForm_Load(object sender, EventArgs e)
            {
    
            }
            void button1_Click(object sender, EventArgs e)
            {
                bw = new BackgroundWorker();
                bw.WorkerReportsProgress = true;
                bw.WorkerSupportsCancellation = true;
    
                bw.DoWork += DoWork;
                bw.RunWorkerCompleted += RunWorkerComplated;
                bw.ProgressChanged += UpdateButtonText;
                bw.RunWorkerAsync();
            }
    
            void RunWorkerComplated(object sender, RunWorkerCompletedEventArgs e)
            {
                MessageBox.Show("ok");
            }
    
            void DoWork(object sender, DoWorkEventArgs e)
            {
                for (int i = 1; i <= 100; i++)
                {
                    (sender as BackgroundWorker).ReportProgress(i);
                    label1.Text = i.ToString();
                    Thread.Sleep(100);
                }
            }
    
            void UpdateButtonText(object sender, ProgressChangedEventArgs e)
            {
    
                button2.Text = e.ProgressPercentage.ToString();
    
            }
    
        }
    }

    走过的弯路:

    1. DoWork方法中不能操纵UI控件。

    2. DoWork事件中调用ReportProgress方法,在ProgressChanged事件中可以操纵UI控件。

    3. WorkerReportsProgress属性必须设置true.   (默认是false. 因为这块,费了不少时间找原因)

  • 相关阅读:
    常用资源
    printf打印颜色
    Vue开发中踩坑-Day3
    Vue开发踩坑-Day2
    Vue开发中的踩坑-day1
    Python中virtualenv的使用
    第十一章:Python高级编程-协程和异步IO
    第十章:Python高级编程-多线程、多进程和线程池编程
    第九章:Python高级编程-Python socket编程
    自定义Element父子不关联的穿梭树
  • 原文地址:https://www.cnblogs.com/Jiaojiawang/p/7484624.html
Copyright © 2011-2022 走看看