Search code examples
winui-3winui

How can I execute code when the application exits?


I try to flush the log on applcation exit. Here is my try, but CoreApplicationExiting is never called:

public partial class App : Application
{
    public App()
    {
        Serilog.Log.Logger = new LoggerConfiguration()
            .WriteTo.Console()
            .WriteTo.File(ApplicationData.Current.LocalFolder.Path + "\\.log", rollingInterval: RollingInterval.Day, 
                outputTemplate: "[{Timestamp:HH:mm:ss.fff} {SourceContext} [{Level}] {Message}{NewLine}{Exception}")
            .MinimumLevel.Debug()
            .CreateLogger();

        Serilog.Log.Information("Starting App at: " + DateTime.Now);

        base.UnhandledException += App_UnhandledException;
        CoreApplication.Exiting += CoreApplicationExiting;
        InitializeComponent();

        Host = Microsoft.Extensions.Hosting.Host
            .CreateDefaultBuilder()
            .UseContentRoot(AppContext.BaseDirectory)
            .UseSerilog()
            .ConfigureServices((context, services) =>
            
            ....
    }
    
     private void CoreApplicationExiting(object? sender, object e)
    {
        Serilog.Log.CloseAndFlush();
    }

I tested that with a button handler and a breakpoint in CoreApplicationExiting.

    private void tryExit(object sender, RoutedEventArgs e)
    {
        Application.Current.Exit();
    }

Solution

  • You could use Window's Closed event.

    protected override void OnLaunched(LaunchActivatedEventArgs args)
    {
        _window = new MainWindow();
        _window.Activate();
        _window.Closed += (sender, args) =>
        {
            // Flush your logs here.
        };
    }