使用控件 BackgroundWorker 的实质是为该进程新创建一个线程来执行耗时操作。
bool changed = false;private void tabControl1_Selected(object sender, TabControlEventArgs e){ changed = true; if (!backgroundWorker1.IsBusy) { if (changed) { backgroundWorker1.RunWorkerAsync(); } }}private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e){ // time-consuming operations int sum = 0; for (int i = 0; i < int.MaxValue; i++) { sum += i; } textBox1.Text = sum.ToString(); // time-consuming operations changed = false;}
与直接创建一个线程相比,BackgroundWorker 不需要忽视控件多线程的安全机制,详见。
还可以使用 BackgroundWorker 异步创建新的窗口:
private void Open_Click(object sender, EventArgs e){ this.backgroundWorker1.RunWorkerAsync();}private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e){ ExternalForm ef = new ExternalForm(); ef.ShowDialog();}