groundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { if (e.Cancelled) { MessageBox.Show("后台任务已取消"); } else if (e.Error != null) { MessageBox.Show("后台任务出现错误: " + e.Error.Message); } else { MessageBox.Show("后台任务完成"); } } private void button1_Click(object sender, EventArgs e) { if (this.backgroundWorker1.IsBusy != true) { // 开始后台工作 this.button1.Text = "取消"; this.backgroundWorker1.RunWorkerAsync(); } else { if (this.backgroundWorker1.CancellationPending == true) { this.backgroundWorker1.CancelAsync(); } else { MessageBox.Show("后台任务正在运行,无法启动"); } } } private void button1_Click_1(object sender, EventArgs e) { this.button1.Text = "开始"; } }}
1