如何开辟一个专用线程控制进度条的循环显示

命名空间:    using System.Threading;

声明委托:    private delegate void SetProgressBarHandler(ProgressBar pb, bool Sign);
             private SetProgressBarHandler changeProgress;

进度条显示标记:
        private bool progressShowSign = true;
        public bool ProgressShowSign
        {
            get { return progressShowSign; }
            set { progressShowSign = value; }
        }

创建委托实例并创建线程调用FunProgress函数控制进度条显示:
        this.changeProgress = new SetProgressBarHandler(this.SetProgressValue);
        Thread thInfor = new Thread(new ThreadStart(this.FunProgress));
        thInfor.Start();

FunProgress函数:
        private void FunProgress()
        {
            while (true)
            {
                lock (typeof(Thread))
                {
                    if (this.progressMain.InvokeRequired)
                    {
                        if (ProgressShowSign)        //progressShowSign值为真时:进度条循环滚动
                        {
                            this.BeginInvoke(this.changeProgress, new object[] { this.progressMain, false });
                            Thread.Sleep(200);
                        }
                        else                //为假时:进度条显示完成.
                        {
                            this.BeginInvoke(this.changeProgress, new object[] { this.progressMain, true });
                            Thread.Sleep(50);
                            break;
                        }
                    }
                }
            }
        }

控制进度条显示的值:
        private void SetProgressValue(ProgressBar pb, bool Sign)
        {
            if (!Sign)
            {
                if (100 == pb.Value)         //进度条value为100时, 自动从0开始
                {
                    pb.Value -= 100;
                }
                pb.PerformStep();            //进度条以1递增
                pb.Refresh();
            else
            {
                while (pb.Value < 100)
                {
                    pb.PerformStep();
                    pb.Refresh();
                }
            }
        }

工作完成后使用    this.ProgressShowSign = false;  即可退出线程.

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