我正在为 WCF 调用(使用 BackgroundWorker)编写某种包装器,以防止 GUI 在调用进行时卡住。它大部分都在正常工作,但是当 WCF 调用抛出异常时,我遇到了 BackgroundWorker 的问题。如果在 DoWork 中发生异常,我可以在 RunWorkCompleted 中检测到它,但是将它重新抛出到 GUI 是行不通的。我读过很多帖子,有人提到这应该有效。
包装器代码(注意 WCF 调用以抛出的异常为标志):
private void GetSomething(Action<IEnumerable<int>> completedAction)
{
BackgroundWorker b = new BackgroundWorker();
b.DoWork += (s, evt) => { throw new Exception(); evt.Result = new List<int> { 1, 2, 3 }; };
b.RunWorkerCompleted += (s, evt) =>
{
if (evt.Error == null && completedAction != null)
{
completedAction((IEnumerable<int>)evt.Result);
}
else if(evt.Error != null)
{
throw evt.Error;
}
};
b.RunWorkerAsync();
}
在 Windows 窗体中调用代码:
private void button3_Click(object sender, EventArgs e)
{
try
{
GetSomething(list =>
{
foreach (int i in list)
{
listView1.Items.Add(new ListViewItem(i.ToString()));
}
});
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
调试时,我得到:
- "Exception of type 'System.Exception' was thrown" in DoWork
- "Exception of type 'System.Exception' was thrown" at throw evt.Error
- "TargetInvocationException was unhandled" at Application.Run(new Form1()) in the Main method
我做错了什么?我想捕获 Windows 窗体中的异常。
最佳答案
你应该改变这个:
抛出 evt.Error;
对此:
MessageBox.Show(evt.Error.Message);
您的异常当前未处理,因为 RunWorkerCompleted
处理程序稍后运行。它不在 button3_Click
中的 try/catch 中运行。
关于c# - BackgroundWorker.RunWorkCompleted - 无法重新抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13212422/