MainLoopSyncContext.cs 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. #nullable disable
  2. namespace Terminal.Gui.App;
  3. /// <summary>
  4. /// provides the sync context set while executing code in Terminal.Gui, to let
  5. /// users use async/await on their code
  6. /// </summary>
  7. internal sealed class MainLoopSyncContext : SynchronizationContext
  8. {
  9. public override SynchronizationContext CreateCopy () { return new MainLoopSyncContext (); }
  10. public override void Post (SendOrPostCallback d, object state)
  11. {
  12. // Queue the task using the modern architecture
  13. ApplicationImpl.Instance.Invoke (() => { d (state); });
  14. }
  15. //_mainLoop.Driver.Wakeup ();
  16. public override void Send (SendOrPostCallback d, object state)
  17. {
  18. if (Thread.CurrentThread.ManagedThreadId == Application.MainThreadId)
  19. {
  20. d (state);
  21. }
  22. else
  23. {
  24. var wasExecuted = false;
  25. Application.Invoke (
  26. () =>
  27. {
  28. d (state);
  29. wasExecuted = true;
  30. }
  31. );
  32. while (!wasExecuted)
  33. {
  34. Thread.Sleep (15);
  35. }
  36. }
  37. }
  38. }