小白在线

爱生活 爱小白

C#【多线程篇】BackgroundWorker类使用总结

using System;
using System.ComponentModel;
using System.Windows.Forms;
 
namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        private BackgroundWorker bgWorker = new BackgroundWorker();
 
        public Form1()
        {
            InitializeComponent();
            InitializeBackgroundWorker();
        }
 
        private void InitializeBackgroundWorker()
        {
            bgWorker.WorkerReportsProgress = true;
            bgWorker.WorkerSupportsCancellation = true;
            bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork);
            bgWorker.ProgressChanged += new ProgressChangedEventHandler(bgWorker_ProgessChanged);
            bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgWorker_WorkerCompleted);
        }
 
   
        public void bgWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            for (int i = 0; i <= 100; i++)
            {
                if (bgWorker.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }
                else
                {
                    bgWorker.ReportProgress(i, "Working");
                    System.Threading.Thread.Sleep(10);
                }
            }
        }
 
        public void bgWorker_ProgessChanged(object sender, ProgressChangedEventArgs e)
        {
            string state =(string)e.UserState;//接收ReportProgress方法传递过来的userState
            this.label2.Text = "状态:" +state;
            this.progressBar1.Value = e.ProgressPercentage;
            this.label1.Text = "处理进度:" + Convert.ToString(e.ProgressPercentage) + "%";
        }
 
        public void bgWorker_WorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show(e.Error.ToString());
                return;
            }
            if (!e.Cancelled)
                this.label1.Text = "处理完毕!";
            else
                this.label1.Text = "处理终止!";
 
        }
     
        private void btnStart_Click_1(object sender, EventArgs e)
        {
            if (bgWorker.IsBusy)
                return;
            this.progressBar1.Maximum = 100;
            this.btnStart.Enabled = false;
            this.btnStop.Enabled = true;
            bgWorker.RunWorkerAsync("hello");
        }
 
        private void btnStop_Click_1(object sender, EventArgs e)
        {
            this.btnStart.Enabled = true;
            this.btnStop.Enabled = false;
            bgWorker.CancelAsync();
        }
    }
}


«    2024年5月    »
12345
6789101112
13141516171819
20212223242526
2728293031
控制面板
您好,欢迎到访网站!
  查看权限
网站分类
搜索
最新留言
    文章归档
    网站收藏
    友情链接
    • Z-BlogPHP
    • 订阅本站的 RSS 2.0 新闻聚合

    Powered By Z-BlogPHP 1.7.3

    Copyright iXiaoBai.net Rights Reserved. 吉ICP备18001369号-1 吉公网安备22010202001107