![](/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.