MainLoopSyncContext.cs 1.7 KB

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