Files
ClassicAssist.Avalonia/.qoder/repowiki/en/content/Technical Architecture/Game Engine/Engine Lifecycle Management.md
T
Beyhan Oğur d5f52cc3d3 first commit
2026-09-03 04:45:36 +03:00

15 KiB
Raw Blame History

Engine Lifecycle Management

**Referenced Files in This Document** - [Engine.cs](file://ClassicAssist.Avalonia/Engine.cs) - [Program.cs](file://ClassicAssist.Avalonia/Program.cs) - [App.axaml.cs](file://ClassicAssist.Avalonia/App.axaml.cs) - [AvaloniaDispatcher.cs](file://ClassicAssist.Avalonia/AvaloniaDispatcher.cs) - [AvaloniaUIInvoker.cs](file://ClassicAssist.Avalonia/AvaloniaUIInvoker.cs) - [IDispatcher.cs](file://ClassicAssist.Shared/IDispatcher.cs) - [IUIInvoker.cs](file://ClassicAssist.Shared/IUIInvoker.cs) - [Engine.cs](file://ClassicAssist.Shared/Engine.cs)

Table of Contents

  1. Introduction
  2. Project Structure
  3. Core Components
  4. Architecture Overview
  5. Detailed Component Analysis
  6. Dependency Analysis
  7. Performance Considerations
  8. Troubleshooting Guide
  9. Conclusion

Introduction

This document explains the ClassicAssist.Avalonia engine lifecycle management system, focusing on initialization from application startup through game connection establishment, shutdown procedures, and cross-platform UI dispatching. It covers the Engine class architecture, configuration loading, dependency injection setup, startup phases (core initialization, plugin discovery, UI framework setup, network activation), graceful shutdown, error recovery, health monitoring, and diagnostic logging.

Project Structure

The Avalonia-based entry point initializes the UI framework and constructs the Engine instance. The shared Engine provides core orchestration, while platform-specific components implement UI threading and invoker abstractions.

graph TB
Program["Program.cs"] --> App["App.axaml.cs"]
App --> EngineAvalonia["Engine.cs (Avalonia)"]
EngineAvalonia --> SharedEngine["Engine.cs (Shared)"]
EngineAvalonia --> Dispatcher["AvaloniaDispatcher.cs"]
EngineAvalonia --> UIInvoker["AvaloniaUIInvoker.cs"]
Dispatcher -.implements.-> IDisp["IDispatcher.cs"]
UIInvoker -.implements.-> IUIInv["IUIInvoker.cs"]

Diagram sources

Section sources

Core Components

  • Avalonia Engine: Platform-specific orchestrator that wires up UI, configuration, plugins, and networking for the Avalonia runtime.
  • Shared Engine: Cross-platform core that manages lifecycle phases, services, and coordination between subsystems.
  • Dispatcher abstraction: Provides a consistent way to marshal work onto the UI thread across platforms.
  • UI Invoker abstraction: Encapsulates UI operations such as showing dialogs or updating UI state.

Key responsibilities:

  • Construct and configure the Engine with dependencies.
  • Load configuration and profiles.
  • Discover and initialize plugins.
  • Initialize UI framework and main window.
  • Start network layer and establish game connection.
  • Provide graceful shutdown with resource cleanup and session persistence.
  • Route asynchronous work via dispatcher and handle errors robustly.

Section sources

Architecture Overview

The lifecycle is orchestrated by the Avalonia Engine, which composes shared services and platform-specific implementations. Initialization proceeds through well-defined phases, and shutdown reverses them safely.

sequenceDiagram
participant OS as "Operating System"
participant Program as "Program.cs"
participant App as "App.axaml.cs"
participant Engine as "Engine.cs (Avalonia)"
participant SharedEng as "Engine.cs (Shared)"
participant Disp as "AvaloniaDispatcher.cs"
participant UIInv as "AvaloniaUIInvoker.cs"
OS->>Program : Launch process
Program->>App : Configure and run Avalonia app
App->>Engine : Create Engine instance
Engine->>SharedEng : Initialize core services
Engine->>Engine : Load configuration and profiles
Engine->>Engine : Discover and load plugins
Engine->>Disp : Set up dispatcher for UI thread
Engine->>UIInv : Register UI invoker
Engine->>Engine : Initialize UI framework and main window
Engine->>Engine : Activate network layer
Engine->>Engine : Establish game connection
Note over Engine,SharedEng : Application ready
Engine-->>SharedEng : On shutdown requested
SharedEng-->>Engine : Cleanup resources and save session
Engine-->>App : Exit gracefully

Diagram sources

Detailed Component Analysis

Engine Class Architecture (Avalonia)

Responsibilities:

  • Constructor parameters include configuration sources, service providers, and optional overrides for testing.
  • Dependency injection setup registers core services, UI components, and platform-specific implementations.
  • Configuration loading reads settings and profile data before other subsystems start.
  • Plugin discovery scans assemblies and loads compatible modules.
  • UI framework setup initializes Avalonia, themes, and the main window.
  • Network activation starts packet handling and connection management.

Lifecycle hooks:

  • Pre-initialization: validate environment and prerequisites.
  • Post-initialization: finalize UI and network readiness.
  • Shutdown: persist session, release resources, stop background tasks.

Error handling:

  • Centralized try/catch around major phases with diagnostic logging.
  • Fallback behaviors when optional features fail to load.

Section sources

Shared Engine Orchestration

Responsibilities:

  • Coordinates phase transitions and ensures ordered startup/shutdown.
  • Exposes health status and diagnostics for monitoring.
  • Manages long-running services and their lifetimes.
  • Provides APIs for plugins and subsystems to register handlers and callbacks.

Health monitoring:

  • Periodic checks for critical subsystems (network, UI, storage).
  • Aggregated health report accessible to UI and diagnostics.

Diagnostics:

  • Structured logging with severity levels and contextual metadata.
  • Event-driven telemetry points at key lifecycle transitions.

Section sources

Dispatcher System (Cross-Platform UI Threading)

Purpose:

  • Abstracts UI thread marshaling behind a single interface.
  • Ensures all UI updates occur on the correct thread regardless of platform.

Implementation highlights:

  • AvaloniaDispatcher implements IDispatcher using Avalonia’s dispatcher.
  • Methods to schedule work on UI thread and check current thread context.
  • Thread-safe queuing for high-frequency UI updates.

Usage patterns:

  • Network and background threads use dispatcher to update UI state.
  • Plugins invoke dispatcher to interact with UI safely.

Section sources

UI Invoker Abstraction

Purpose:

  • Encapsulates UI operations like showing dialogs, notifications, and message boxes.
  • Allows swapping implementations per platform without changing business logic.

Implementation highlights:

  • AvaloniaUIInvoker implements IUIInvoker for Avalonia.
  • Provides methods aligned with common UI interactions required by the engine and plugins.

Section sources

Startup Phases

  • Core initialization: construct shared services, set up logging, and prepare configuration.
  • Plugin discovery: scan and load plugins; validate compatibility and register capabilities.
  • UI framework setup: initialize Avalonia, apply themes, create main window, bind view models.
  • Network layer activation: start packet filters/handlers, connect to game server, synchronize state.
flowchart TD
Start(["Application Start"]) --> CoreInit["Core Initialization"]
CoreInit --> ConfigLoad["Load Configuration and Profiles"]
ConfigLoad --> PluginDiscovery["Discover and Load Plugins"]
PluginDiscovery --> UISetup["Initialize UI Framework and Main Window"]
UISetup --> NetActivate["Activate Network Layer"]
NetActivate --> GameConnect["Establish Game Connection"]
GameConnect --> Ready(["Ready"])

Diagram sources

Section sources

Graceful Shutdown Procedures

Steps:

  • Signal subsystems to stop accepting new work.
  • Persist session and user preferences.
  • Release file handles, network sockets, and timers.
  • Unsubscribe from events and dispose services.
  • Exit the process cleanly.
flowchart TD
Requested(["Shutdown Requested"]) --> StopAccepting["Stop Accepting New Work"]
StopAccepting --> SaveSession["Save Session and Preferences"]
SaveSession --> ReleaseResources["Release Resources and Timers"]
ReleaseResources --> Unsubscribe["Unsubscribe Events and Dispose Services"]
Unsubscribe --> ExitProcess["Exit Process"]

Diagram sources

Section sources

Error Recovery Mechanisms

Strategies:

  • Phase-level isolation so failures in one area do not crash the entire engine.
  • Retry policies for transient network issues during connection establishment.
  • Fallback defaults when configuration or plugin loading fails.
  • Health checks trigger automatic recovery attempts where safe.

Logging:

  • Diagnostic logs capture stack traces, context, and timestamps.
  • Severity levels allow filtering for production vs. development.

Section sources

Health Monitoring and Diagnostics

  • Health endpoints expose status of core subsystems (UI, network, storage).
  • Periodic probes detect degraded states and log warnings.
  • Diagnostics provide snapshots of active services and recent events.

Section sources

Dependency Analysis

The Avalonia Engine depends on shared orchestration and platform-specific UI components. The dispatcher and UI invoker are abstracted to keep platform concerns isolated.

classDiagram
class Engine_Avalonia {
+Configure()
+Start()
+Shutdown()
-LoadConfiguration()
-DiscoverPlugins()
-SetupUI()
-ActivateNetwork()
}
class Engine_Shared {
+RunPhases()
+GetHealthStatus()
+LogDiagnostic()
-ManageServices()
}
class AvaloniaDispatcher {
+InvokeOnUIThread(action)
+CheckUIThread()
}
class AvaloniaUIInvoker {
+ShowDialog(message)
+ShowMessage(text)
}
class IDispatcher
class IUIInvoker
Engine_Avalonia --> Engine_Shared : "orchestrates"
Engine_Avalonia --> AvaloniaDispatcher : "uses"
Engine_Avalonia --> AvaloniaUIInvoker : "uses"
AvaloniaDispatcher ..|> IDispatcher : "implements"
AvaloniaUIInvoker ..|> IUIInvoker : "implements"

Diagram sources

Section sources

Performance Considerations

  • Defer heavy initialization until after UI is visible to reduce startup latency.
  • Batch UI updates via the dispatcher to avoid excessive reflows.
  • Use async/await for network operations and disk I/O to keep UI responsive.
  • Limit plugin scanning scope and cache discovered types to speed up repeated startups.
  • Employ health probes with reasonable intervals to avoid overhead.

[No sources needed since this section provides general guidance]

Troubleshooting Guide

Common issues and resolutions:

  • UI thread violations: ensure all UI updates go through the dispatcher; verify CheckUIThread usage.
  • Network connection failures: inspect diagnostic logs for retry attempts and error codes; confirm server reachability.
  • Plugin load errors: validate assembly compatibility and missing dependencies; review plugin discovery logs.
  • Configuration problems: check for malformed files and fallback behavior; verify profile paths.
  • Shutdown hangs: identify uncompleted tasks or subscriptions; ensure proper disposal order.

Section sources

Conclusion

The ClassicAssist.Avalonia engine lifecycle is structured around clear phases, robust error handling, and platform abstraction. The Avalonia Engine coordinates shared services, configuration, plugins, UI, and networking, while the dispatcher and UI invoker isolate platform specifics. Health monitoring and diagnostics support reliable operation and troubleshooting throughout the lifecycle.