如何处理BackgroundWorker处理程序中引发的异常?
我认为BackgroundWorker对象会捕获DoWork处理程序中引发的异常并将其传递给RunWorkerCompleted处理程序,但我的程序并没有发生这种情况。
我创建了以下小程序来说明该问题。创建了 wpf 应用程序。
公共部分类 MainWindow : 窗口 { 公共主窗口() { 初始化组件(); ExecBackgrpundWorker(); bw_DoWork 中引发的异常
public void ExecBackgrpundWorker()
{
var bw = new BackgroundWorker();
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
bw.RunWorkerAsync();
}
void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
try
{
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
void bw_DoWork(object sender, DoWorkEventArgs e)
{
throw new NotImplementedException("Do Work Exception");
}
}
永远不会传递给 bw_RunWorkerCompleted。
如何正确处理这个异常。
I thought that the BackgroundWorker object will trap and pass exceptions raised in the DoWork handler to the RunWorkerCompleted hanlder but it is not happening to my program.
I created the following small program to illustrate the problem. Created wpf app.
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
ExecBackgrpundWorker();
}
public void ExecBackgrpundWorker()
{
var bw = new BackgroundWorker();
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
bw.RunWorkerAsync();
}
void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
try
{
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
void bw_DoWork(object sender, DoWorkEventArgs e)
{
throw new NotImplementedException("Do Work Exception");
}
}
exceptions raised in the bw_DoWork is never passed to the bw_RunWorkerCompleted.
How to properly handle this exception.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
该异常被后台线程捕获并分配给 RunWorkerCompleted 的 RunWorkerCompletedEventArgs 参数的“Error”属性。
The exception is catched by the background thread and assigned to the "Error" property of the RunWorkerCompletedEventArgs parameter of RunWorkerCompleted.
它永远不会进入“RunWorkerCompleted”处理程序。
它正在悄然失败。
我的示例是检查 Active Directory 中的安全组列表。
我输入了一个无效的域来测试错误处理...无声。
It never makes it to "RunWorkerCompleted" handler.
it is failing silently.
My example is checking Active Directory for a list of security groups.
I've entered an invalid domain to test the error handling... silent.
将代码更改为:
如果您调试并得到 Exception was unhanded by user code,请单击“继续”,然后您将到达 bw_RunWorkerCompleted。当您以发布形式运行代码时,它将始终到达 bw_RunWorkerCompleted。
Change your code to:
If you debugging and get Exception was unhanded by user code, click Continue then you will reach bw_RunWorkerCompleted. When you run your code as release it will always get to bw_RunWorkerCompleted.