多线程更新进度条的疑问

.Net技术 码拜 9年前 (2016-07-12) 1161次浏览
        private Class A
        {
            private ProgressBar proBar;
            public A(ProgressBar bar)
            {
                proBar = bar;
            }
            
            public void SaveImg()
            {
                //保存图片
                Dowork();
            }
            private delegate void DoWorkDelegate();
            public void DoWork()
            {
                if (proBar.InvokeRequired)
                {
                    DoWorkDelegate d = DoWork;
                    proBar.Invoke(d);
                }
                else
                {
                    proBar.Value++;
                    Application.DoEvents();
                    //if()
                }
            }
        }
  //在Button点击事件中循环实例化线程
       for(int i =0 ; i<=1000 ; i++)
       {
           Thread DownLoadPicThread = new Thread(new ThreadStart(imgInfo.FormatImg));
           DownLoadPicThread.Start();
        }

问题:
1、DoWork函数执行proBar.Invoke(d)后会等全部的图片保存了之后再更新进度条proBar,为什么会这样。是原因是实例太多的线程,没有空闲时间吗,还是原因是其他的?谢谢!

解决方案

20

那1000各线程运行的是啥?dowork还是递归的?啥意思啊,没看明白

20

proBar.Invoke(d);
改为
proBar.BeginInvoke(d);
试试呢

10

 proBar.Value++;
Application.DoEvents();
这里输出日志看看。

50

演示代码,参考一

namespace CSDemo.Test
{
    public partial class FormTest : Form
    {
        public FormTest()
        {
            InitializeComponent();
        }
        A a;
        private void button1_Click(object sender, EventArgs e)
        {
            progressBar1.Value = 0;
            progressBar1.Maximum = 1000;
            a = new A(progressBar1);
            new Thread(() => {
                for (int i = 0; i < 1000; i++)
                {
                    Thread DownLoadPicThread = new Thread(new ThreadStart(a.SaveImg));
                    DownLoadPicThread.Start();
                }
            }).Start();
        }
        class A
        {
            private ProgressBar proBar;
            public A(ProgressBar bar)
            {
                proBar = bar;
            }
            public void SaveImg()
            {
                Thread.Sleep(new Random().Next(10000));
                //保存图片
                DoWork();
            }
            private delegate void DoWorkDelegate();
            public void DoWork()
            {
                if (proBar.InvokeRequired)
                {
                    DoWorkDelegate d = DoWork;
                    proBar.Invoke(d);
                }
                else
                {
                    proBar.Value++;
                    //Application.DoEvents();
                    //if()
                }
            }
        }
    }
}

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明多线程更新进度条的疑问
喜欢 (0)
[1034331897@qq.com]
分享 (0)