在 App.axaml.cs 中,App类添加下列事件;
1.重写 OnFrameworkInitializationCompleted ,会在程序初始化完成后触发
2. 绑定AppDomain中当前域的事件
AppDomain.CurrentDomain.UnhandledException += HandleGlobalException; //UI线程
AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit;//非UI线程
public override void OnFrameworkInitializationCompleted()
{
try
{
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{
var main = new MainWindow();
main.DataContext = new VM_MainWindow(main);
desktop.MainWindow = main;
}
else if (ApplicationLifetime is ISingleViewApplicationLifetime singleViewPlatform)
{
var main = new MainView();
singleViewPlatform.MainView = main;
}
base.OnFrameworkInitializationCompleted();
//全局异常捕获
AppDomain.CurrentDomain.UnhandledException += HandleGlobalException;
AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit;
}
catch(Exception ex)
{
LogOperate.Error("程序启动发生异常", ex);
Environment.Exit(0);
}
}
private void CurrentDomain_ProcessExit(object? sender, EventArgs e)
{
ThreadOperate.OnExit();
}
private void HandleGlobalException(object sender, UnhandledExceptionEventArgs e)
{
try
{
// 处理全局异常的逻辑
Exception exception = (Exception)e.ExceptionObject;
//Console.WriteLine($"Unhandled Exception: {exception.Message}");
LogOperate.Error("HandleGlobalException 全局异常", exception);
}
catch(Exception ex)
{
LogOperate.Error("HandleGlobalException 全局异常[catch]", ex);
}
}