OnIdle 事件中的异常不会冒泡
在我的主窗体上,我订阅了两个事件:Application.ThreadException 和 Application.Idle。理论上,任何未捕获的异常都应该冒泡到主窗体。但是,如果异常发生在 OnIdle 事件中,则此方法不起作用。系统就崩溃了。有谁知道如何解决这个问题?非常感谢。
On my main form, I subscribed to two events: Application.ThreadException and Application.Idle. In theory, any exception that is not caught should get bubbled up to the main form. However, this does not work if the exception happens in the OnIdle event. The system just crashes. Does anyone know how to solve this problem? Thanks so much.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我同意不获取 ThreadException 事件并不是很合乎逻辑。然而,它确实以这种方式工作,仅当消息循环调度事件并且事件处理程序中存在未处理的异常时才会引发 ThreadException。当不再有消息要分派时,会引发 Idle 事件,它遵循完全不同的代码路径。
您可以通过自己在 Idle 事件处理程序中捕获异常来解决这个问题:
请注意,如果您让用户决定是退出还是继续程序,那么 ThreadException 是一件喜忧参半的事情。另请注意,它不够通用,无法捕获程序中的所有异常,您仍然需要 AppDomain.CurrentDomain.UnhandledException 来处理 UI 线程以外的线程中引发的异常或之前引发的异常消息循环开始运行。
如果您这样做是为了确保用户不能单击“继续”,那么只需使用 Application.SetUnhandledExceptionMode() 来完全禁用 ThreadException 事件。现在一切都通过 AppDomain.UnhandledException 进行。这是更好的方法。
I agree it is not terribly logical to not get the ThreadException event. It does however work this way, a ThreadException is only raised when the message loop dispatches an event and there's an unhandled exception in the event handler. The Idle event is raised when there is no message to be dispatched anymore, it follows an entirely different code path.
You can work around it by trapping exceptions in your Idle event handler yourself:
Beware that ThreadException is rather a mixed blessing if you let the user decide whether to quit or continue the program. Also note that it isn't universal enough to catch all exceptions in your program, you still need AppDomain.CurrentDomain.UnhandledException to deal with exceptions raised in threads other than the UI thread or exceptions that are raised before the message loop starts running.
If you are doing this to make sure the user can not click "Continue" then simply use Application.SetUnhandledExceptionMode() to disable the ThreadException event completely. Now everything goes through AppDomain.UnhandledException. It is the better way.
异常只会在被调用方法的堆栈中冒泡。
Idle 事件不是从您的表单代码中调用的,因此不会冒泡到您的任何代码。
相反,您必须捕获未处理的异常。
看一下:
其中之一将捕获您的异常。
Exceptions only bubble up the stack of called methods.
The Idle event is not called from your form code, and thus won't be bubbling up to any of your code.
Instead you'll have to catch unhandled exceptions.
Take a look at:
One of those will trap your exception.