What is the difference between AppDomain.UnhandledException and Application.DispatcherUnhandledException in .NET?开发者_C百科
I need an event that is fired when any unhandled exception occurs. I have come across these two, but I dont know in what ways they differ from each other. Also, are there cases when they are not fired?
Application.DispatcherUnhandledException
will handle exceptions thrown on the main UI thread in a WPF application. AppDomain.UnhandledException
will handle exceptions thrown on any thread and never caught. This includes threads you create manually or the main thread in a Console application. WPF is catching the exceptions on the UI thread, so you will not see those in AppDomain.UnhandledException
.
Also note that unhandled exceptions typically terminate the runtime, so after AppDomain.UnhandledException
is raised your program will immediately exit. In contrast, Application.DispatcherUnhandledException
is catching exceptions and will let your program continue.
DispatcherUnhandledException is raised only by the UI thread and only if an exception was raised while running an event. There's a bit of a tradition to handle these kind of exceptions specially, Windows Forms has it too with Application.ThreadException (poorly named, nothing to do with threads).
The reason is that there is a minor chance to handle the exception and keep the program alive since UI event handlers don't always mutate the state of program too dramatically. This takes large helpings of wishful thinking. Windows Forms takes this to an extreme, it displays a ThreadExceptionDialog that has a Continue button, allowing the user to ignore the exception. WPF does not do that, you'd have to write a dialog like that yourself. Which is why the event is there.
The default action of DispatcherUnhandledException is to not catch the exception. So you're okay to ignore it, AppDomain.UnhandledException will fire next.
http://msdn.microsoft.com/en-us/library/system.windows.application.dispatcherunhandledexception.aspx
says:
"DispatcherUnhandledException is raised by an Application for each exception that is unhandled by code running on the main UI thread."
http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception.aspx
says:
"This event can be handled in any application domain. However, the event is not necessarily raised in the application domain where the exception occurred."
So DispatcherUnhandledException is for UI thread exceptions, and AppDomain.UnhandledException is for everything else.
Hope that helps!
精彩评论