📄 OutGridTree/AvaloniaManager.cs
using System;
using System.Threading;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Threading;

namespace OutGridTree;

internal static class AvaloniaManager
{
    private static readonly Lazy<Task> appBuilder = new(
        static () =>
        {
            var tcs = new TaskCompletionSource<object>();
            var t = new Thread(() =>
                AppBuilder
                    .Configure<Application>()
                    .UsePlatformDetect()
                    .AfterPlatformServicesSetup(_ => tcs.SetResult(new()))
                    .Start((app, _) => app.Run(CancellationToken.None), [])
            );
            t.Start();
            return tcs.Task;
        },
        LazyThreadSafetyMode.ExecutionAndPublication
    );

    public static TWindow OpenWindow<TWindow>()
        where TWindow : Window, new()
    {
        appBuilder.Value.Wait();

        return Dispatcher.UIThread.Invoke(() =>
        {
            var window = new TWindow();
            window.Show();

            return window;
        });
    }
}