简体   繁体   English

在托管的Winforms控件中发生异常后,在WPF应用程序中继续执行

[英]Continuing execution in WPF app after an exception in a hosted Winforms control

I have a WPF app that has a WindowsFormsHost in which a 3rd party WinForms control is hosted. 我有一个WPF应用程序,它有一个WindowsFormsHost,其中托管了第三方WinForms控件。 Sometimes, because of a bug in the 3rd party WinForms control I get a NullReferenceException . 有时,由于第三方WinForms控件中的错误,我得到一个NullReferenceException

Although I had set up a DispatcherUnhandledException handler I can't catch the exception there and continue the execution. 虽然我已经设置了DispatcherUnhandledException处理程序,但我无法在那里捕获异常并继续执行。

Only in the AppDomain.CurrentDomain.UnhandledException handler I can "catch" it but I cannot do much from then on, the application simply exits. 只有在AppDomain.CurrentDomain.UnhandledException处理程序中我才能“抓住”它,但从那时起我就做不了多少,应用程序就会退出。

Then I found a stackoverflow question (with an answer; can't find it now) which stated to try to do this : 然后我发现了一个stackoverflow问题 (有一个答案;现在找不到) ,说明试图这样做:

        System.Windows.Forms.Application.ThreadException += (sender, args) => { /* Catch it here */};
        System.Windows.Forms.Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

That didn't help either because the (inline) handler did not get called ever. 这也没有帮助,因为(内联)处理程序没有被调用过。

Am I going the wrong way ? 走错了路吗?

I am not sure why that handler never gets called in your case, probably because the exception was not thrown on a Windows Forms thread (the thread on which your forms and controls have been created), but generally, setting up handlers for DispatcherUnhandledException , AppDomain.UnhandledException and/or Application.ThreadException doesn't allow you to prevent the termination of the process. 我不确定为什么在你的情况下永远不会调用该处理程序,可能是因为在Windows Forms线程(创建表单和控件的线程)上没有抛出异常,但通常是为DispatcherUnhandledExceptionAppDomain.UnhandledException设置处理程序AppDomain.UnhandledException和/或Application.ThreadException不允许您阻止进程终止。 They are event handlers, not exception handlers. 它们是事件处理程序,而不是异常处理程序。 The unhandled exception is still an unhandled exception even if you have setup those event handlers. 即使您已设置了这些事件处理程序,未处理的异常仍然是未处理的异常。 Usually they are used to add some final logging or present a meaningful message to the user. 通常它们用于添加一些最终日志记录或向用户显示有意义的消息。 Once an unhandled exception is raised there is nothing you can do to prevent the termination of the process. 一旦出现未处理的异常,您就无法阻止该过程的终止。

Maybe the exception thrown is a CSE (Corrupted State Exception). 也许抛出的异常是CSE(Corrupted State Exception)。 To handle these kinds of exceptions, use [HandleProcessCorruptedStateExceptions] attribute for that function. 要处理这些类型的异常,请为该函数使用[HandleProcessCorruptedStateExceptions]属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM