【发布时间】:2020-05-25 17:55:01
【问题描述】:
我已经在应用程序启动中对此进行了编码
在App.xaml.cs内
public App()
{
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);
DispatcherUnhandledException += App_DispatcherUnhandledException;
Application.Current.DispatcherUnhandledException += new DispatcherUnhandledExceptionEventHandler(Application_DispatcherUnhandledException);
TaskScheduler.UnobservedTaskException += new EventHandler<UnobservedTaskExceptionEventArgs>(Application_DispatcherUnhandledException2);
this.Dispatcher.UnhandledException += Dispatcher_UnhandledException;
}
private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
writeMessage(e.Exception);
}
private void Dispatcher_UnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
writeMessage(e.Exception);
}
private static void writeMessage(Exception e)
{
string srMsg = e.InnerException?.Message;
if (srMsg != null)
{
srMsg += "\r\n\r\nStack\r\n" + e.InnerException?.StackTrace;
}
if (srMsg == null)
{
srMsg = e.Message + "\r\n\r\nStack\r\n" + e.StackTrace;
}
srMsg += "\r\n\r\n*********\r\n\r\n";
File.AppendAllText("global_errors.txt", srMsg);
}
private static void Application_DispatcherUnhandledException2(object o, UnobservedTaskExceptionEventArgs e)
{
writeMessage(e.Exception);
}
private static void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
writeMessage(e.Exception);
}
private static void MyHandler(object sender, UnhandledExceptionEventArgs args)
{
Exception e = (Exception)args.ExceptionObject;
writeMessage(e);
}
但是,这仍然没有捕获任务工厂错误
例如
此线程中的任何建议均无效WPF global exception handler
【问题讨论】:
-
这不是一个未处理的异常。任务包装器捕获并保存异常。您可以尝试将按钮单击的签名更改为
private async void Button_Click,然后执行await Task.Run(() => test.Example(););。虽然不能在这里测试它,所以不确定它是否会工作。这里注意,除非某些特殊情况,Task.Run是TaskFactory.StartNew的替换:devblogs.microsoft.com/pfxteam/… -
您看过AppDomain.FirstChanceException 事件吗?过去,我成功地在任何线程中捕获了“未处理的异常”。唯一的缺点是,无论您是否使用 try 和 catch,您都会得到 any 抛出的错误。
-
@Knoop 添加等待肯定会解决问题,但随后我的屏幕变得无响应,因为它锁定了主线程
-
@Twenty 它捕获了错误,但我不明白为什么会发生错误。输入字符串的格式不正确。堆栈在 System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)。它显示消息而不是堆栈跟踪
-
嗯,我自己测试了一下,我得到了 StackTrace 和
FirstChanceExceptionEventArgs。你确定e.Exception.StackTrace为空吗?
标签: c# .net wpf exception task-parallel-library