我有一个背景工作者:
private readonly BackgroundWorker _importWorker = new BackgroundWorker() { WorkerReportsProgress = true };
在我的构造函数中,我做了:
_importWorker.DoWork += _importWorker_DoWork;
_importWorker.ProgressChanged += _importWorker_ProgressChanged;
_importWorker.RunWorkerCompleted += _importWorker_RunWorkerCompleted;
以下是代表:
private void _importWorker_DoWork(object sender, DoWorkEventArgs e)
{
var args = (object[]) e.Argument;
var walletColumnName = (string) args[0];
var fundColumnName = (string) args[1];
var isinColumName = (string) args[2];
var marketValueDirtyColumnName = (string) args[3];
var seperator = (string) args[4];
var importFilePath = (string) args[5];
var importFile = Path.GetFileName(importFilePath);
var onePercent = 100.0 / File.ReadLines(importFilePath).Count();
var totalPercentage = 0.0;
var parser = new TextFieldParser(importFilePath);
parser.TextFieldType = FieldType.Delimited;
parser.SetDelimiters(seperator);
//Read colum indexes on the first line
var fields = parser.ReadFields();
var walletColumnIndex = Array.IndexOf(fields, walletColumnName);
var fundColomnIndex = Array.IndexOf(fields, fundColumnName);
var isinColumnIndex = Array.IndexOf(fields, isinColumName);
var marketValueDirtyColumnIndex = Array.IndexOf(fields, marketValueDirtyColumnName);
if (walletColumnIndex == -1 || fundColomnIndex == -1 || isinColumnIndex == -1 ||
marketValueDirtyColumnIndex == -1)
{
throw new ArgumentException("Eén of meerdere kolommen niet gevonden in " + importFile);
}
//TODO
e.Result = importFile;
}
private void _importWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
Progress = e.ProgressPercentage;
}
private void _importWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
Messenger.Default.Send(e.Error);
}
else if (e.Result != null)
{
PenultimateImportFileName = LastImportFileName;
PenultimateImportDate = LastImportDate;
LastImportFileName = e.Result.ToString();
LastImportDate = ImportDate;
_dataContainer.UpdateImportSettings(_importSettings);
}
Progress = 100;
IsBusy = false;
}
当抛出异常时,backroundworker不会调用e.Error,而是应用程序崩溃。这是正常的,如何解决?我读到当在dowork中抛出未处理的异常时,会自动调用E.Error。
这就是我称之为背景工作者的方式:
_importWorker.RunWorkerAsync(new object[] {WalletColumnName, FundColumnName, IsinColumName, MarketValueDirtyColumnName, Seperator, s});
调试器会中断并抛出我抛出代码的异常:
System.ArgumentException was unhandled by user code
HResult=-2147024809
Message=Eén of meerdere kolommen niet gevonden in 021214-0.txt
Source=Selection Monitoring Tool
StackTrace:
at Selection_Monitoring_Tool.ViewModels.SettingsViewModel._importWorker_DoWork(Object sender, DoWorkEventArgs e) in c:\Users\Joost\Desktop\Selection Monitoring Tool\Selection Monitoring Tool\ViewModels\SettingsViewModel.cs:line 216
at System.ComponentModel.BackgroundWorker.OnDoWork(DoWorkEventArgs e)
at System.ComponentModel.BackgroundWorker.WorkerThreadStart(Object argument)
InnerException:
答案 0 :(得分:0)
正如@HansPassant建议的那样,我必须取消选中“当这个例外类型是用户unhandeled时中断”复选框。