首页 > 编程技术 > csharp

详解WPF中的APP生命周期以及全局异常捕获

发布时间:2023-3-3 15:46 作者:步、步、为营

APP生命周期

wpf项目目录中有一个App.xaml.cs文件,该文件中App是一个partical类,与之对应的另一partical部分在App.g.i.cs文件中,该文件是在编译的时候WPF自动生成的。程序的入口Main方法在该文件中定义。

[System.STAThreadAttribute()]
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "7.0.1.0")]
public static void Main() {
    WpfApp.App app = new WpfApp.App();
    app.InitializeComponent();//初始化Xaml
    app.Run();//程序运行
}

APP类继承自Application,常见的生命周期事件有以下几个:

对于普通窗体程序,从开始到结束会依次调用如下事件

-----App_Startup
-----App_Navigating
-----App_Activated
-----App_Exit

窗体生命周期事件

在APP运行后,会启动窗体,窗体常用的声明周期事件如下:

全局异常捕获

对于异常捕获一般使用try-catch语句进行捕获,但是对于全局的异常可以在App中进行捕获。

案例:

APP中进行全局异常捕获

public partial class App : Application
{
    public App()
    {
        //在异常由应用程序引发但未进行处理时发生。UI线程
        //无法捕获多线程异常
        this.DispatcherUnhandledException += App_DispatcherUnhandledException;
        //专门捕获所有线程中的异常
        AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
        //专门捕获Task异常
        TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
    }
    private void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
    {
        Debug.WriteLine("-----App_DispatcherUnhandledException--UI线程" + e.Exception.Message);
    }
    private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
        Debug.WriteLine("-----CurrentDomain_UnhandledException--其他线程" + (e.ExceptionObject as Exception).Message);
    }
    private void TaskScheduler_UnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs e)
    {
        Debug.WriteLine("-----TaskScheduler_UnobservedTaskException--Task测试" + e.Exception.Message);
        e.SetObserved();
    }
}

窗体中抛异常

public partial class MainWindow : Window
{
    int i = 0;
    public MainWindow()
    {
        InitializeComponent();
        //1、ui线程异常测试
        _ = 1 / i;

        //2、其他线程异常测试
        new Thread(new ThreadStart(() => { _ = 1 / i; })).Start();

        //3、Task异常测试
        Task.Run(() =>
        {
            _ = 1 / i;
        });
    }   
}

异常结果说明
只打开异常1-----App_DispatcherUnhandledException--UI线程-----CurrentDomain_UnhandledException--其他线程UI线程中的异常DispatcherUnhandledException和AppDomain.CurrentDomain.UnhandledException均能捕获到
只打开异常2-----CurrentDomain_UnhandledException--其他线程只有AppDomain.CurrentDomain.UnhandledException可以捕获
只打开异常3-----TaskScheduler_UnobservedTaskException--Task测试只有TaskScheduler.UnobservedTaskException可以捕获到Task异常

备注:Task中的异常并不是立刻就能捕获到的,而是等到垃圾回收的时候进行捕获。如果想立刻进行捕获则可以调用GC.Collect(0);GC.WaitForPendingFinalizers();

到此这篇关于详解WPF中的APP生命周期以及全局异常捕获的文章就介绍到这了,更多相关WPF生命周期 全局异常捕获内容请搜索猪先飞以前的文章或继续浏览下面的相关文章希望大家以后多多支持猪先飞!

原文出处:https://www.cnblogs.com/qsnn/p/17068129.html

标签:[!--infotagslink--]

您可能感兴趣的文章: