Exception in the OnIdle event does not bubble up

烂漫一生 提交于 2019-12-12 12:02:00

问题


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.


回答1:


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);
        }
    }

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.




回答2:


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:

  1. Application.ThreadException
  2. AppDomain.UnhandledException

One of those will trap your exception.



来源:https://stackoverflow.com/questions/2876748/exception-in-the-onidle-event-does-not-bubble-up

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!