在 App.axaml.cs 中,App类添加下列事件;
1.重写 OnFrameworkInitializationCompleted ,会在程序初始化完成后触发
2. 绑定AppDomain中当前域的事件文章来源:https://www.toymoban.com/news/detail-855992.html
AppDomain.CurrentDomain.UnhandledException += HandleGlobalException; //UI线程
AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit;//非UI线程文章来源地址https://www.toymoban.com/news/detail-855992.html
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);
}
}
到了这里,关于Avalonia 捕获全局异常(UI线程 和 非UI线程),增加客户端的稳定性的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!