C# 通过委托控制进度条以及多线程更新控件

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace Demo0004
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        //线程开始的时候调用的委托
        private delegate void maxValueDelegate(int maxValue);
        //线程执行中调用的委托
        private delegate void nowValueDelegate(int nowValue);

        private void button1_Click(object sender, EventArgs e)
        {
            ThreadMethod method = new ThreadMethod();
            //先订阅一下事件
            method.threadStartEvent += new EventHandler(method_threadStartEvent);
            method.threadEvent += new EventHandler(method_threadEvent);
            method.threadEndEvent += new EventHandler(method_threadEndEvent);

            Thread thread = new Thread(new ThreadStart(method.runMethod));
            thread.Start();
        }

        /// <summary>
        /// 线程开始事件,设置进度条最大值
        /// 但是我不能直接操作进度条,需要一个委托来替我完成
        /// </summary>
        /// <param name="sender">ThreadMethod函数中传过来的最大值</param>
        /// <param name="e"></param>
        void method_threadStartEvent(object sender, EventArgs e)
        {
            int maxValue = Convert.ToInt32(sender);
            maxValueDelegate max = new maxValueDelegate(setMax);
            this.Invoke(max, maxValue);
        }

        /// <summary>
        /// 线程执行中的事件,设置进度条当前进度
        /// 但是我不能直接操作进度条,需要一个委托来替我完成
        /// </summary>
        /// <param name="sender">ThreadMethod函数中传过来的当前值</param>
        /// <param name="e"></param>
        void method_threadEvent(object sender, EventArgs e)
        {
            int nowValue = Convert.ToInt32(sender);
            nowValueDelegate now = new nowValueDelegate(setNow);
            this.Invoke(now, nowValue);
        }

        /// <summary>
        /// 线程完成事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void method_threadEndEvent(object sender, EventArgs e)
        {
            MessageBox.Show("执行已经完成!");
        }

        /// <summary>
        /// 我被委托调用,专门设置进度条最大值的
        /// </summary>
        /// <param name="maxValue"></param>
        private void setMax(int maxValue)
        {
            this.progressBar1.Maximum = maxValue;
        }

        /// <summary>
        /// 我被委托调用,专门设置进度条当前值的
        /// </summary>
        /// <param name="nowValue"></param>
        private void setNow(int nowValue)
        {
            this.progressBar1.Value = nowValue;
        }
    }


    public class ThreadMethod
    {
        /// <summary>
        /// 线程开始事件
        /// </summary>
        public event EventHandler threadStartEvent;
        /// <summary>
        /// 线程执行时事件
        /// </summary>
        public event EventHandler threadEvent;
        /// <summary>
        /// 线程结束事件
        /// </summary>
        public event EventHandler threadEndEvent;

        public void runMethod()
        {
            int count = 100;      //执行多少次
            threadStartEvent.Invoke(count, new EventArgs());//通知主界面,我开始了,count用来设置进度条的最大值
            for (int i = 0; i < count; i++)
            {
                Thread.Sleep(100);//休息100毫秒,模拟执行大数据量操作
                threadEvent.Invoke(i, new EventArgs());//通知主界面我正在执行,i表示进度条当前进度
            }
            threadEndEvent.Invoke(new object(), new EventArgs());//通知主界面我已经完成了
        }
    }
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace Demo0004
{
    public partial class Form2 : Form
    {
        //在下载窗体上面 建一个委托
        public delegate void ChangeProgress(int value); //进度条
        public delegate void ChangeButton(int value); //按钮
        //创建上面的委托的变量
        public ChangeProgress changeProgerss;
        public ChangeButton changebtn;

        public Form2()
        {
            InitializeComponent();
            //为这个委托变量赋值
            changeProgerss = FunChangeProgress;
            changebtn = FunChangebutton;
        }

        //通过创建工作线程消除用户界面线程的阻塞问题 
        private void button1_Click(object sender, EventArgs e)
        {
            button1.Enabled = false;
            //新创建一个线程
            System.Threading.Thread thr = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(Download));
            thr.Start();            
        }

        //线程方法 一定要是object 类型参数 同时返回值是void
        private void Download(object obj)
        {
            for (int i = 0; i <= 100; i++)
            {
                //执行委托 更新按钮  -重点
                this.button1.Invoke(changebtn, i);
                //执行委托 更新进度条  -重点
                this.progressBar1.Invoke(changeProgerss, i);
                System.Threading.Thread.Sleep(100);
            }
        }

        //更新进度条
        public void FunChangeProgress(int value)
        {
            progressBar1.Value = value;
        }

        //更新按钮
        public void FunChangebutton(int value)
        {
            if (value == 100)
            {
                button1.Text = "开始新进程";
                button1.Enabled = true;
            }
            else
            {
                //相除保留两位小数 且四舍五入 Math.Round(1.00 * value / 100, 2,MidpointRounding.AwayFromZero)
                button1.Text = Math.Round(1.00 * value / 100, 2,MidpointRounding.AwayFromZero) * 100 + "%";
            }
        }

        //窗体关闭 强制退出 销毁所有相关进程
        private void Form2_FormClosing(object sender, FormClosingEventArgs e)
        {
            //强制退出 销毁进程
            System.Environment.Exit(System.Environment.ExitCode);
            this.Dispose();
            this.Close();
        }
    }
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Demo0004
{
    public partial class Form3 : Form
    {
        public delegate void ChangeStatus();
        //创建上面的委托的变量  
        public ChangeStatus changestatus;
        public Form3()
        {
            InitializeComponent();
        }

        private void Form3_Load(object sender, EventArgs e)
        {
            //使用Timer组件实现多线程定时同步
            System.Timers.Timer t = new System.Timers.Timer(3000);   //实例化Timer类,设置间隔时间单位毫秒; 
            t.Elapsed += new System.Timers.ElapsedEventHandler(UpdateWork); //到达时间的时候执行事件;   
            t.AutoReset = true;   //设置是执行一次(false)还是一直执行(true);   
            t.Enabled = true;     //是否执行System.Timers.Timer.Elapsed事件;   
            changestatus = FunChangeStatus;  
        }

        private void UpdateWork(object source, System.Timers.ElapsedEventArgs e)
        {
            this.Invoke(changestatus);
        }

        //更新
        public void FunChangeStatus()
        {
            #region 更新开始
            //更新方法
            #endregion
            lbtimer.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " 数据更新成功";
        }
    }
}


原文地址:https://www.cnblogs.com/smartsmile/p/6234185.html