![](/img/trans.png)
[英]WPF - error handling with asynchronous command using BackgroundWorker
[英]Error handling condition using BackGroundWorker Fails
为了习惯于我的项目并使用Backgroundworker
进行培训,我使用了一个示例代码,该代码可以平稳运行,除非要处理错误状况,否则它不允许我使用RunWorkerCompletedEventArgs e
(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)
我的程序不会private void RunWorkerCompleted(object sender, ,RunWorkerCompletedEventArgs e)
。 在其他情况下(取消,成功完成),它会正确执行。
使用
Backgroundworker
为我的项目习惯并接受培训
为什么要这么做? 在所有方面, Task.Run()
都比BackgroundWorker
更好。
现在回答您的实际问题:在BackgroundWorker
导致错误,在.Net中使用标准机制:例外:
if (this.simulateError)
{
this.simulateError = false;
throw new Exception("Simulating error.");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.