diff --git a/App.xaml.cs b/App.xaml.cs index ca24e02..fffa489 100644 --- a/App.xaml.cs +++ b/App.xaml.cs @@ -3,6 +3,7 @@ using System.Configuration; using System.Data; using System.Windows; using System.Windows.Controls; +using System.Windows.Threading; namespace SunlightAggregationManager { @@ -11,7 +12,58 @@ namespace SunlightAggregationManager /// public partial class App : Application { - + protected override void OnStartup(StartupEventArgs e) + { + base.OnStartup(e); + RegisterGlobalExceptionHandlers(); + } + + private void RegisterGlobalExceptionHandlers() + { + // 1. 捕获 UI 主线程的未处理异常 + this.DispatcherUnhandledException += App_DispatcherUnhandledException; + + // 2. 捕获非 UI 线程(后台线程)的未处理异常 + AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; + + // 3. 捕获 Task 异步任务中的未观察到的异常 + TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException; + } + + // UI线程异常处理 + private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) + { + LogAndShowError("UI线程发生异常", e.Exception); + + // 【关键】将 Handled 设为 true,告诉 WPF 该异常已被处理,阻止程序自动闪退 + e.Handled = true; + } + + // 非UI线程异常处理 + private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) + { + var exception = e.ExceptionObject as Exception; + bool isTerminating = e.IsTerminating; + + LogAndShowError($"非UI线程异常 (即将终止: {isTerminating})", exception); + + // 注意:此事件不允许设置 Handled=true,默认情况下致命异常仍会导致程序退出 + } + + // Task线程异常处理 + private void TaskScheduler_UnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs e) + { + LogAndShowError("Task异步任务异常", e.Exception); + + // 标记异常已被观察,防止它被重新抛出导致进程终止 + e.SetObserved(); + } + + private void LogAndShowError(string context, Exception ex) + { + // 在这里记录日志或弹出友好的自定义错误提示窗口 + MessageBox.Show($"{context}:\n{ex?.Message}", "程序遇到错误", MessageBoxButton.OK, MessageBoxImage.Error); + } } }