MainLoopSyncContext.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. Application.MainLoop?.TimedEvents.Add (TimeSpan.Zero,
  13. () =>
  14. {
  15. d (state);
  16. return false;
  17. }
  18. );
  19. Application.MainLoop?.Wakeup ();
  20. }
  21. //_mainLoop.Driver.Wakeup ();
  22. public override void Send (SendOrPostCallback d, object state)
  23. {
  24. if (Thread.CurrentThread.ManagedThreadId == Application.MainThreadId)
  25. {
  26. d (state);
  27. }
  28. else
  29. {
  30. var wasExecuted = false;
  31. Application.Invoke (
  32. () =>
  33. {
  34. d (state);
  35. wasExecuted = true;
  36. }
  37. );
  38. while (!wasExecuted)
  39. {
  40. Thread.Sleep (15);
  41. }
  42. }
  43. }
  44. }