为了适应和训练我的项目使用Backgroundworker,我使用了一个运行流畅的示例代码,除了在处理错误情况时,它不允许我使用RunWorkerCompletedEventArgs e.I的(e.Error!=null)工具,我想要像取消和成功完成的方式一样为我处理错误。
请给我建议!代码如下:
private void DoWork(object sender, DoWorkEventArgs e)
{
Random rand = new Random();
for (int i = 0; i < 10; i++)
{
if (this.backgroundWorker.CancellationPending)
{
e.Cancel = true;
break;
}
// report progress
this.backgroundWorker.ReportProgress(-1, string.Format("Performing step {0}...", i + 1));
// simulate operation step
System.Threading.Thread.Sleep(rand.Next(1000, 10000));
//setting simulateError to true after inducing error(a button)
if (this.simulateError)
{
this.simulateError = false;
//needs a code to use (e.Error!=null) in
RunWorkerCompleted().
//A jump to RunWorkerCompleted is required here.
}
}
}
private void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// hide animation
this.pictureBox.Image = null;
// show result indication
if (e.Cancelled)
{
////works nice
this.labelProgress.Text = "Operation cancelled by the user!";
this.pictureBox.Image = Properties.Resources.WarningImage;
}
else
{
//doesn't execute at all....why?
if (e.Error != null)
{
this.labelProgress.Text = "Operation failed: " + e.Error.Message;
this.pictureBox.Image = Properties.Resources.ErrorImage;
}
else
{
//works nice
this.labelProgress.Text = "Operation finished successfuly!";
this.pictureBox.Image = Properties.Resources.InformationImage;
}
}
// restore button states
this.buttonStart.Enabled = true;
this.buttonCancel.Enabled = false;
this.buttonError.Enabled = false;
}我使用simulateError导致错误,为了显示特殊的错误信息,我应该如何使用
if (e.Error != null)
{
this.labelProgress.Text = "Operation failed: " + e.Error.Message;如果出现错误,我的程序不会进入private void RunWorkerCompleted(object sender, ,RunWorkerCompletedEventArgs e)。在其他情况下(取消、成功完成),它会正确执行。
发布于 2015-04-10 03:00:33
为我的项目使用Backgroundworker来适应和接受培训的
你为什么要这么做?Task.Run() is better than BackgroundWorker in every way.
现在来看您的实际问题:要在BackgroundWorker中导致错误,请使用.Net中的标准机制: exceptions:
if (this.simulateError)
{
this.simulateError = false;
throw new Exception("Simulating error.");
}https://stackoverflow.com/questions/28483740
复制相似问题