码迷,mamicode.com
首页 > 其他好文 > 详细

backgroundWorker1

时间:2020-06-26 15:00:19      阅读:77      评论:0      收藏:0      [点我收藏+]

标签:threading   img   async   windows   ace   取消   mod   col   sync   

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

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


技术图片

技术图片



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";
        }
     }
}

backgroundWorker1

标签:threading   img   async   windows   ace   取消   mod   col   sync   

原文地址:https://www.cnblogs.com/xe2011/p/13194684.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!