Skip to main content
Avalonia provides a flexible application lifetime management system that adapts to different application types, from desktop applications with windows to mobile single-view apps.

Lifetime Interfaces

Avalonia supports multiple application lifetime models through different interfaces:

IClassicDesktopStyleApplicationLifetime

Traditional desktop applications with multiple windows, main window, and explicit shutdown.

ISingleViewApplicationLifetime

Mobile and embedded applications with a single view.

ISingleTopLevelApplicationLifetime

Applications with a single top-level window (desktop or mobile).

IControlledApplicationLifetime

Base interface providing programmatic shutdown control.

Classic Desktop Lifetime

The most common lifetime for desktop applications is IClassicDesktopStyleApplicationLifetime.

Configuration

Program.cs
using Avalonia;
using System;

class Program
{
    [STAThread]
    public static void Main(string[] args) => BuildAvaloniaApp()
        .StartWithClassicDesktopLifetime(args);

    public static AppBuilder BuildAvaloniaApp()
        => AppBuilder.Configure<App>()
            .UsePlatformDetect()
            .LogToTrace();
}

Initialization Sequence

When you call StartWithClassicDesktopLifetime(), the following sequence occurs:
1. AppBuilder.Setup() → Initialize platform services
2. Application.RegisterServices() → Register core services
3. Application.Initialize() → Load XAML resources
4. Startup event fired → Application started
5. MainWindow.Show() → Display main window
6. Dispatcher.UIThread.MainLoop() → Enter message loop
7. Application exits → Shutdown process begins

Setting the Main Window

App.axaml.cs
using Avalonia;
using Avalonia.Controls.ApplicationLifetimes;

public class App : Application
{
    public override void OnFrameworkInitializationCompleted()
    {
        if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
        {
            desktop.MainWindow = new MainWindow
            {
                DataContext = new MainWindowViewModel()
            };
        }

        base.OnFrameworkInitializationCompleted();
    }
}

Shutdown Modes

Desktop applications support three shutdown modes:
ShutdownMode Enum
public enum ShutdownMode
{
    OnLastWindowClose,    // Exit when all windows are closed
    OnMainWindowClose,    // Exit when main window closes
    OnExplicitShutdown    // Exit only on Shutdown() call
}

Configuration Example

Setting ShutdownMode
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{
    desktop.ShutdownMode = ShutdownMode.OnMainWindowClose;
    desktop.MainWindow = new MainWindow();
}
The default ShutdownMode is OnLastWindowClose, which exits the application when all windows are closed.

Lifetime Events

Startup Event

Fired when the application starts, before the main window is shown:
Handling Startup
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{
    desktop.Startup += (sender, e) =>
    {
        // Access command line arguments
        var args = e.Args;
        
        // Perform initialization
        InitializeServices();
        LoadConfiguration();
    };
}

ShutdownRequested Event

Fired when shutdown is requested, can be cancelled:
Handling Shutdown Request
desktop.ShutdownRequested += (sender, e) =>
{
    // Check if there's unsaved work
    if (HasUnsavedChanges())
    {
        var result = ShowConfirmationDialog(
            "You have unsaved changes. Exit anyway?");
            
        if (result == DialogResult.Cancel)
        {
            e.Cancel = true;  // Prevent shutdown
        }
    }
};
The ShutdownRequested event is not fired when using Shutdown() with force. Only TryShutdown() allows cancellation.

Exit Event

Fired when the application is about to exit (cannot be cancelled):
Handling Exit
desktop.Exit += (sender, e) =>
{
    // Clean up resources
    CloseConnections();
    SaveSettings();
    
    // Access (and modify) exit code
    Console.WriteLine($"Exiting with code: {e.ApplicationExitCode}");
    
    // Can change exit code if needed
    if (errorOccurred)
        e.ApplicationExitCode = 1;
};

Programmatic Shutdown

TryShutdown Method

Attempts to shut down the application, can be cancelled by event handlers:
TryShutdown Example
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{
    // Request shutdown (can be cancelled)
    bool shutdownSucceeded = desktop.TryShutdown(exitCode: 0);
    
    if (shutdownSucceeded)
    {
        Console.WriteLine("Application is shutting down");
    }
    else
    {
        Console.WriteLine("Shutdown was cancelled");
    }
}

Shutdown Method

Forces application shutdown, cannot be cancelled:
Force Shutdown
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{
    // Force shutdown (cannot be cancelled)
    desktop.Shutdown(exitCode: 0);
}

Window Management

The desktop lifetime tracks all open windows:
Working with Windows
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{
    // Access all open windows
    IReadOnlyList<Window> windows = desktop.Windows;
    
    // Enumerate windows
    foreach (var window in windows)
    {
        Console.WriteLine($"Window: {window.Title}");
    }
    
    // Find specific window
    var settingsWindow = windows
        .OfType<SettingsWindow>()
        .FirstOrDefault();
}
Windows are automatically added to the Windows collection when shown and removed when closed.

Complete Lifecycle Example

using Avalonia;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Markup.Xaml;

public class App : Application
{
    public override void Initialize()
    {
        AvaloniaXamlLoader.Load(this);
    }

    public override void OnFrameworkInitializationCompleted()
    {
        if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
        {
            // Configure shutdown mode
            desktop.ShutdownMode = ShutdownMode.OnMainWindowClose;
            
            // Handle startup
            desktop.Startup += OnStartup;
            
            // Handle shutdown request
            desktop.ShutdownRequested += OnShutdownRequested;
            
            // Handle exit
            desktop.Exit += OnExit;
            
            // Set main window
            desktop.MainWindow = new MainWindow
            {
                DataContext = new MainWindowViewModel()
            };
        }

        base.OnFrameworkInitializationCompleted();
    }
    
    private void OnStartup(object? sender, ControlledApplicationLifetimeStartupEventArgs e)
    {
        // Initialize services, parse arguments
        var args = e.Args;
        // ...
    }
    
    private void OnShutdownRequested(object? sender, ShutdownRequestedEventArgs e)
    {
        // Check for unsaved work, can cancel
        if (HasUnsavedWork())
        {
            e.Cancel = !ConfirmExit();
        }
    }
    
    private void OnExit(object? sender, ControlledApplicationLifetimeExitEventArgs e)
    {
        // Final cleanup
        SaveApplicationState();
    }
}

Platform-Specific Shutdown

OS Shutdown Events

Avalonia handles OS-level shutdown requests (e.g., Windows logoff, macOS shutdown):
Handling OS Shutdown
desktop.ShutdownRequested += (sender, e) =>
{
    if (e.IsOSShutdown)
    {
        // OS is shutting down
        // Save critical data immediately
        QuickSave();
        
        // Can still cancel if needed
        // e.Cancel = true;
    }
};

Advanced Scenarios

Setup Without Starting

For testing or custom scenarios, you can set up without starting:
Setup Only
var lifetime = new ClassicDesktopStyleApplicationLifetime
{
    ShutdownMode = ShutdownMode.OnExplicitShutdown
};

AppBuilder.Configure<App>()
    .UsePlatformDetect()
    .SetupWithLifetime(lifetime);

// Application is configured but not running
// Manually start later:
// lifetime.Start(args);

Custom Lifetime Implementation

You can create custom lifetime implementations:
Custom Lifetime
public class CustomApplicationLifetime : IApplicationLifetime
{
    // Implement custom lifetime behavior
}

// Use in AppBuilder
var customLifetime = new CustomApplicationLifetime();
builder.SetupWithLifetime(customLifetime);

Best Practices

1

Choose the right shutdown mode

Use OnMainWindowClose for single-window apps, OnLastWindowClose for multi-window apps.
2

Handle shutdown gracefully

Use ShutdownRequested to save data and confirm exit. Use Exit for final cleanup.
3

Use TryShutdown for user actions

When the user requests exit, use TryShutdown() to allow cancellation. Reserve Shutdown() for fatal errors.
4

Track application state

Use Startup and Exit events to load and save application state.

Build docs developers (and LLMs) love