winfrom 多线程+委托更新ui(进度读条为例)

        //定义一个委托
        private delegate void DelegateFunction(int ipos);
        private Thread multi = null;
        private void button1_Click(object sender, EventArgs e)
        {
            progressBar1.Visible = true;
            //设置进度条最大小值 
            this.progressBar1.Maximum = 10000;
             this.progressBar1.Minimum = 0;
            if (multi != null && multi.IsAlive)
            {
                return;
            }
            multi = new Thread(new ThreadStart(StartWork));
            multi.IsBackground = true;
            multi.Start();


        }

        private void Form1_Load(object sender, EventArgs e)
        {
            progressBar1.Visible = false;
        }
        //执行函数
        int sumNum = 0;
        private void StartWork()
        {

            sumNum = 10000;
            for (int i = 1; i <= 10000; i++)
            {
                //...........
                //在这里执行一个非常非常耗时的函数 DoLongTimeWork()
                //DoLongTimeWork();
                //...........
                for (int ii = 0; ii < 1000000; ii++)
                {
                    
                }

                SetPos(i); //关键就在这里,只有将要更改progressBar的value的时候 才去Invoke 这样就不会一直占用着主界面的刷新  
            }
        }
        //设置进度条的Value
        private void SetPos(int ipos)
        {
           
            if (this.progressBar1.InvokeRequired)
            {
                    DelegateFunction df = new DelegateFunction(SetPos);
                    this.BeginInvoke(df, new object[] { ipos });
            }
            else
            {
                progressBar1.Value = ipos;
                if (ipos == sumNum)
                {
                    progressBar1.Visible = false;
                
                }
            }


        }

你可能感兴趣的:(C#)