And*_*nea 5 wpf exception windowsformshost winforms
我有一个 WPF 应用程序,它有一个 WindowsFormsHost,其中托管了一个 3rd 方 WinForms 控件。有时,由于 3rd 方 WinForms 控件中的错误,我会得到一个NullReferenceException
.
尽管我已经设置了一个DispatcherUnhandledException
处理程序,但我无法在那里捕获异常并继续执行。
只有在AppDomain.CurrentDomain.UnhandledException
处理程序中我才能“捕获”它,但从那时起我不能做太多事情,应用程序只是退出。
然后我发现了一个 stackoverflow 问题 (有答案;现在找不到),它说要尝试这样做:
System.Windows.Forms.Application.ThreadException += (sender, args) => { /* Catch it here */};
System.Windows.Forms.Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
Run Code Online (Sandbox Code Playgroud)
这也无济于事,因为(内联)处理程序从未被调用过。
我走错路了吗?
我不确定为什么在您的情况下该处理程序永远不会被调用,可能是因为异常没有在Windows 窗体线程(创建表单和控件的线程)上引发,但通常为 DispatcherUnhandledException
,AppDomain.UnhandledException
和/设置处理程序或者Application.ThreadException
不允许您阻止进程的终止。它们是事件处理程序,而不是异常处理程序。即使您已经设置了这些事件处理程序,未处理的异常仍然是未处理的异常。通常它们用于添加一些最终日志记录或向用户呈现有意义的消息。一旦引发未处理的异常,您就无法阻止进程终止。