MainLoopSyncContext.cs 1.4 KB

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