窗体拉一个Button按钮和一个加载等待显示的label,
label默认隐藏,点击按钮时显示这个label,加载完再隐藏
1、工具箱拉BackgroundWorker控件到窗体
2、backgroundWorker1属性-闪电图标-双击点进去DoWork事件和RunWorkerCompleted事件
public partial class Ceshi2 : Form { public Ceshi2() { InitializeComponent(); CheckForIllegalCrossThreadCalls = false;//Dowork()方法里有控件会报异常 } private void button1_Click(object sender, EventArgs e) { label1.Visible = true; backgroundWorker1.RunWorkerAsync();//开始后台操作,引发DoWork事件 } //调用 RunWorkerAsync 方法时发生 private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { for (int i = 0; i < 5; i++) { Thread.Sleep(1000); } } //后台操作已完成、被取消或引发异常时发生 private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { label1.Visible = false; }
}
异常1:线程间操作无效: 从不是创建控件的线程访问它,在构造方法里加这一行即可
public Ceshi2() { InitializeComponent(); CheckForIllegalCrossThreadCalls = false;//Dowork()方法里有控件会报异常 }
如果哪里有异常,try...catch()...
异常2:在某个线程上创建的控件不能成为在另一个线程上创建的控件的父级
try { //代码 } catch (ArgumentException ex) { }