wpf 从任何线程捕获未处理的异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15526992/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Catch unhandled exceptions from any thread
提问by Tono Nam
Edit
编辑
The answers to this question where helpful thanks I appreciate the help :) but I ended up using: http://code.msdn.microsoft.com/windowsdesktop/Handling-Unhandled-47492d0b#content
这个问题的答案有帮助谢谢我感谢帮助:) 但我最终使用了:http: //code.msdn.microsoft.com/windowsdesktop/Handling-Unhandled-47492d0b#content
Original question:
原问题:
I want to show a error message when my application crashes.
我想在应用程序崩溃时显示错误消息。
Currently I have:
目前我有:
App.xaml:
App.xaml:
<Application x:Class="WpfApplication5.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
DispatcherUnhandledException="App_DispatcherUnhandledException" // <----------------
StartupUri="MainWindow.xaml">
<Application.Resources>
</Application.Resources>
</Application>
Code-behind of App.xaml:
代码隐藏App.xaml:
namespace WpfApplication5
{
public partial class App : Application
{
private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
MessageBox.Show("Caught Unhandled Exception!");
}
}
}
That solution works great when the error occurs on the main thread. Now my problem is how will I be able to catch errors that happen on a different thread also?
当错误发生在主线程上时,该解决方案非常有效。现在我的问题是我如何才能捕捉到发生在不同线程上的错误?
In other words: when I press this button I am able to catch the exception: (App_DispatcherUnhandledExceptiongets called!)
换句话说:当我按下这个按钮时,我能够捕捉到异常:(App_DispatcherUnhandledException被调用!)
private void button1_Click(object sender, RoutedEventArgs e)
{
int.Parse("lkjdsf");
}
But I am not able to catch this exception:
但我无法捕捉到这个异常:
private void button1_Click(object sender, RoutedEventArgs e)
{
Task.Factory.StartNew(() =>
{
int.Parse("lkjdsf");
});
}
How will I be able to catch all exceptions regardless if they happen on the main thread or not?
无论它们是否发生在主线程上,我如何才能捕获所有异常?
回答by Tilak
You can use AppDomain.UnhandledExceptionHandlerto handle uncaught exception.
您可以使用AppDomain.UnhandledExceptionHandler来处理未捕获的异常。
回答by omer schleifer
Use AppDomain.UnhandledException event to catch this exception. than you need to use the dispatcher to be able to show this exception in a messageBox (this is because only ui thread can show messages)
使用 AppDomain.UnhandledException 事件捕获此异常。比您需要使用调度程序才能在 messageBox 中显示此异常(这是因为只有 ui 线程可以显示消息)

