MainLoopSyncContext.cs 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  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 using the modern architecture
  12. ApplicationImpl.Instance.Invoke (() => { d (state); });
  13. }
  14. //_mainLoop.Driver.Wakeup ();
  15. public override void Send (SendOrPostCallback d, object state)
  16. {
  17. if (Thread.CurrentThread.ManagedThreadId == Application.MainThreadId)
  18. {
  19. d (state);
  20. }
  21. else
  22. {
  23. var wasExecuted = false;
  24. Application.Invoke (
  25. () =>
  26. {
  27. d (state);
  28. wasExecuted = true;
  29. }
  30. );
  31. while (!wasExecuted)
  32. {
  33. Thread.Sleep (15);
  34. }
  35. }
  36. }
  37. }