private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
var count = (int)e.Argument;
for (int i = 1; i <= count; i++)
{
if (backgroundWorker1.CancellationPending)
{
e.Cancel = true;
return;
}
//if (i == 2)
// throw new Exception("出错啦!");
backgroundWorker1.ReportProgress(i);
//任务
Thread.Sleep(500);//模拟耗时的任务
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
toolStripProgressBar1.Value = e.ProgressPercentage;
toolStripStatusLabel1.Text = DateTime.Now.ToString();
}
//更新UI,异常处理
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
toolStripStatusLabel1.Text += "任务取消。";
else if (e.Error != null)
toolStripStatusLabel1.Text += "出现异常: " + e.Error;
else
toolStripStatusLabel1.Text += "任务完成。 ";
}
private void button1_Click(object sender, EventArgs e)
{
if (!backgroundWorker1.IsBusy)
{
toolStripProgressBar1.Value = 0;
toolStripProgressBar1.Maximum = 100;
toolStripStatusLabel1.Text = "任务开始...";
//标记
backgroundWorker1.RunWorkerAsync(100);
}
else
{
MessageBox.Show("正在进行异步操作.");
}
}
private void button2_Click(object sender, EventArgs e)
{
backgroundWorker1.CancelAsync();
}