Application.MainLoopSyncContext.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. namespace Terminal.Gui;
  2. public static partial class Application
  3. {
  4. /// <summary>
  5. /// provides the sync context set while executing code in Terminal.Gui, to let
  6. /// users use async/await on their code
  7. /// </summary>
  8. private sealed class MainLoopSyncContext : SynchronizationContext
  9. {
  10. public override SynchronizationContext CreateCopy () { return new MainLoopSyncContext (); }
  11. public override void Post (SendOrPostCallback d, object state)
  12. {
  13. MainLoop?.AddIdle (
  14. () =>
  15. {
  16. d (state);
  17. return false;
  18. }
  19. );
  20. }
  21. //_mainLoop.Driver.Wakeup ();
  22. public override void Send (SendOrPostCallback d, object state)
  23. {
  24. if (Thread.CurrentThread.ManagedThreadId == _mainThreadId)
  25. {
  26. d (state);
  27. }
  28. else
  29. {
  30. var wasExecuted = false;
  31. Invoke (
  32. () =>
  33. {
  34. d (state);
  35. wasExecuted = true;
  36. }
  37. );
  38. while (!wasExecuted)
  39. {
  40. Thread.Sleep (15);
  41. }
  42. }
  43. }
  44. }
  45. }