AppManager.cs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. using System;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4. using Avalonia.Themes.Fluent;
  5. using Avalonia.Threading;
  6. namespace Avalonia.IntegrationTests.Win32.Infrastructure;
  7. internal static class AppManager
  8. {
  9. private static readonly Lazy<Task<Dispatcher>> s_initTask = new(CreateUIThread, LazyThreadSafetyMode.ExecutionAndPublication);
  10. private static readonly CancellationTokenSource s_cancellation = new();
  11. public static void Stop()
  12. => s_cancellation.Cancel();
  13. private static Task<Dispatcher> CreateUIThread()
  14. {
  15. var tcs = new TaskCompletionSource<Dispatcher>();
  16. var uiThread = new Thread(() =>
  17. {
  18. var appBuilder = AppBuilder
  19. .Configure<Application>()
  20. .UseWin32()
  21. .UseSkia()
  22. .SetupWithoutStarting();
  23. appBuilder.Instance!.Styles.Add(new FluentTheme());
  24. // Ensure that Dispatcher.UIThread is initialized on this thread
  25. var dispatcher = Dispatcher.UIThread;
  26. dispatcher.VerifyAccess();
  27. tcs.TrySetResult(dispatcher);
  28. dispatcher.MainLoop(s_cancellation.Token);
  29. })
  30. {
  31. Name = "UI Thread"
  32. };
  33. uiThread.Start();
  34. return tcs.Task;
  35. }
  36. public static Task<Dispatcher> EnsureAppInitializedAsync()
  37. => s_initTask.Value;
  38. }