问题
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:
- Application.ThreadException
- AppDomain.UnhandledException
One of those will trap your exception.
来源:https://stackoverflow.com/questions/2876748/exception-in-the-onidle-event-does-not-bubble-up