C# 多线程实现ProgressBar效果 先说明下我的程序要实现的功能,我要是实现的是下面这个窗体下填写好一些基本信息,选择好日志文件,然后分析日志文件。但是这个分析是调用另一个类中的分析日志程序,后台数据比较大,这也使得前台许久不能更新,界面卡死现象,所以我用了多线程来解决这个问题。 多线程实现起来也方便,下面是部分代码 Thread thread = new Thread(new ThreadStart(doLog));//线程加入doLog函数 if (thread.ThreadState ==ThreadState.Unstarted) { thread.IsBackground = true; thread.Start(); } private void doLog() { WebLogUtil webLogUtil = new WebLogUtil(this);//注意这里,WebLogUtil的构造函数,我是用this传参 string webfile = txtLogAdr.Text.Trim(); int webid = int.Parse(txtId.Text.Trim()); if (Directory.Exists(webfile)) { string[] files = Directory.GetFiles(webfile, '*.log'); proBar.Maximum = files.Length; for (int i = 0; i < Directory.GetFiles(webfile, '*.log').Length; i++) { webLogUtil.readLog(webfile + '\\' + files[i], webid); proBar.Value += 1; } } else { webLogUtil.readLog(webfile, webid);//分析日志函数调用 } } 这个分析日志的功能基本已经搞定了,但是怎么实现ProgressBar的效果呢,我们要动态的给progressBar设置Value值,下面还有一个函数就是 public void setProgressBar(int Max,int value) { proBar.Minimum = 0; if (proBar.Maximum != Max) proBar.Maximum = Max; proBar.Value = value; } 这个函数就是用来设置ProgressBar的值的。但是我们的设置值不能在窗体下面设置,因为设置ProgressBar的进度要看这个分析日志函数的进度来设置。但是这个分析日志函数在WebLogUtil类中,我们又怎么来将这两个函数连接在一起使用呢??大家请看红色那一行,应该就明白了,用this传参,这样就可以在WebLogUtil类中的readLog函数体内调用setProgressBar();来实现ProgressBar的Value改变。 到这里,问题还没完呢,为什么呢? 大家应该都知道,前台UI控件由单独的线程控制,这时也就是说有两个线程了线程间是不容许互相交错反问的,线程间操作无效。其实有一个简单的方法可以解决,窗体的构造函数里加入 Control.CheckForIllegalCrossThreadCalls = false; 这句来容许线程间操作。实现是很容易,但是安全性很低,一旦线程变多,这样操作必然有问题,我们也可以使用 control.Invoke这里就不说了。 |
|