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);
试试呢
改为
proBar.BeginInvoke(d);
试试呢
10
proBar.Value++;
Application.DoEvents();
这里输出日志看看。
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() } } } } }