using System.Windows; using System.Windows.Threading; using Chronos.Ui.Theming; namespace Chronos.App.Tests.Windows; /// /// The process-wide WPF (only one may ever exist per process) on its own STA thread with /// the Chronos theme. Every WPF test reaches it through here, whichever test happens to run first. /// internal static class WpfApplication { private static readonly Lazy<(Dispatcher Dispatcher, Thread Thread)> Instance = new(Start, LazyThreadSafetyMode.ExecutionAndPublication); public static Dispatcher Dispatcher => Instance.Value.Dispatcher; /// /// Stops the dispatcher in order (its binding engine and windows clean up on their own thread) and waits for it, so the /// process exits without WPF work racing its teardown. Nothing to do when no WPF test ran. /// public static void Shutdown() { if (!Instance.IsValueCreated) return; var (dispatcher, thread) = Instance.Value; if (!dispatcher.HasShutdownStarted) dispatcher.InvokeShutdown(); thread.Join(TimeSpan.FromSeconds(10)); } private static (Dispatcher, Thread) Start() { Dispatcher? dispatcher = null; using var ready = new ManualResetEventSlim(); var thread = new Thread(() => { var app = new Application { ShutdownMode = ShutdownMode.OnExplicitShutdown }; ThemeManager.Initialize(app, AppTheme.Dark); dispatcher = System.Windows.Threading.Dispatcher.CurrentDispatcher; ready.Set(); System.Windows.Threading.Dispatcher.Run(); }); thread.SetApartmentState(ApartmentState.STA); thread.IsBackground = true; thread.Start(); ready.Wait(); return (dispatcher!, thread); } }