gpt4 book ai didi

c# - BackgroundWorker.RunWorkCompleted - 无法重新抛出异常

转载 作者:行者123 更新时间:2023-11-30 12:48:54 25 4
gpt4 key购买 nike

我正在为 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);
}
}

调试时,我得到:

  1. "Exception of type 'System.Exception' was thrown" in DoWork
  2. "Exception of type 'System.Exception' was thrown" at throw evt.Error
  3. "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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com