日期:2014-05-17 浏览次数:21022 次
常常为了WINFORM进度条和其他控件联动所烦恼,下面代码将解决这个问题。
//俩个进程共享数据 private volatile int d = 1; private volatile int bc = 0;
private void button1_Click(object sender, EventArgs e) { //Form加载的时候启动一个手工线程. System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(NumberIncrement)); thread.Start(); }
private void NumberIncrement() {//数据执行流程 int[,] arr = new int[100, 2]; for (int i = 0; i < 100; i++) { Random dm = new Random(); arr[i, 0] = i; int sd = dm.Next(1, 10); arr[i, 1] = sd; d = i; bc = sd; EventHandler eh = new EventHandler(DisplayNumber); this.Invoke(eh, new object[] { null, null }); Thread.Sleep(sd * 500); } }
private void DisplayNumber(object sender, EventArgs e) { //这里给UI控件赋值. label1.Text = "正在执行第" +(d+1).ToString() + "记录,花费时间为" + bc.ToString(); progressBar1.Value = d; }