OnIdle事件中的异常不会冒泡 [英] Exception in the OnIdle event does not bubble up

查看:120
本文介绍了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.

推荐答案

我同意不获取ThreadException事件并不是很逻辑。但是,它确实以这种方式工作,仅当消息循环调度事件并且事件处理程序中存在未处理的异常时,才会引发ThreadException。当不再发送任何消息时,将引发Idle事件,它遵循完全不同的代码路径。

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:

    void Application_Idle(object sender, EventArgs e) {
        try {
            // Do stuff
        }
        catch (Exception ex) {
            Application.OnThreadException(ex);
        }
    }

请注意,如果让ThreadException成为一种混合祝福,用户决定是退出还是继续该程序。还要注意,在程序中捕获 all 异常还不够通用,您仍然需要AppDomain.CurrentDomain.UnhandledException来处理除UI线程以外的其他线程中引发的异常或之前引发的异常。消息循环开始运行。

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.

如果要执行此操作以确保用户不能 单击继续,则只需使用Application.SetUnhandledExceptionMode ()完全禁用ThreadException事件。现在,所有内容都通过AppDomain.UnhandledException处理。这是更好的方法。

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.

这篇关于OnIdle事件中的异常不会冒泡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆