C# 异步控制进度条

来源:互联网 发布:整容价格知乎 编辑:程序博客网 时间:2024/06/03 17:15
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 MyPrograssBar{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();        }        // 定义委托,异步调用        delegate void ShowProgressDelegate(int totalStep, int currentStep);        private void button1_Click(object sender, EventArgs e)        {            ParameterizedThreadStart start = new ParameterizedThreadStart(SetProgress);            Thread progressThread = new Thread(start);            progressThread.IsBackground = true;             progressThread.Start();        }        /// <summary>        /// 设置当前进度        /// </summary>        /// <param name="state"></param>        void SetProgress(object state)        {            for (int i = 1; i <= 100; i++)            {                Thread.Sleep(200);                // 异步调用                this.Invoke(new ShowProgressDelegate(ShowProgress), new object[] { 100, i });            }        }        /// <summary>        /// 刷新进度条        /// </summary>        /// <param name="totalStep"></param>        /// <param name="currentStep"></param>        void ShowProgress(int totalStep, int currentStep)        {            this.progressBar1.Maximum = totalStep;            this.progressBar1.Value = currentStep;            this.label1.Text = this.progressBar1.Value * 100 / progressBar1.Maximum + "%";        }        private void button2_Click(object sender, EventArgs e)        {            ThreadStart start = new ThreadStart(ThreadTest);            Thread testThread = new Thread(start);            testThread.IsBackground = true;             testThread.Start();        }        private void ThreadTest()        {            for (int i = 1; i <= 100; i++)            {                Thread.Sleep(200);            }            MessageBox.Show("Hello world!");        }    }}

0 0