GodotTaskScheduler.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6. namespace Godot
  7. {
  8. public class GodotTaskScheduler : TaskScheduler
  9. {
  10. private GodotSynchronizationContext Context { get; set; }
  11. private readonly LinkedList<Task> _tasks = new LinkedList<Task>();
  12. public GodotTaskScheduler()
  13. {
  14. Context = new GodotSynchronizationContext();
  15. SynchronizationContext.SetSynchronizationContext(Context);
  16. }
  17. protected sealed override void QueueTask(Task task)
  18. {
  19. lock (_tasks)
  20. {
  21. _tasks.AddLast(task);
  22. }
  23. }
  24. protected sealed override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
  25. {
  26. if (SynchronizationContext.Current != Context)
  27. {
  28. return false;
  29. }
  30. if (taskWasPreviouslyQueued)
  31. {
  32. TryDequeue(task);
  33. }
  34. return TryExecuteTask(task);
  35. }
  36. protected sealed override bool TryDequeue(Task task)
  37. {
  38. lock (_tasks)
  39. {
  40. return _tasks.Remove(task);
  41. }
  42. }
  43. protected sealed override IEnumerable<Task> GetScheduledTasks()
  44. {
  45. lock (_tasks)
  46. {
  47. return _tasks.ToArray();
  48. }
  49. }
  50. public void Activate()
  51. {
  52. ExecuteQueuedTasks();
  53. Context.ExecutePendingContinuations();
  54. }
  55. private void ExecuteQueuedTasks()
  56. {
  57. while (true)
  58. {
  59. Task task;
  60. lock (_tasks)
  61. {
  62. if (_tasks.Any())
  63. {
  64. task = _tasks.First.Value;
  65. _tasks.RemoveFirst();
  66. }
  67. else
  68. {
  69. break;
  70. }
  71. }
  72. if (task != null)
  73. {
  74. if (!TryExecuteTask(task))
  75. {
  76. throw new InvalidOperationException();
  77. }
  78. }
  79. }
  80. }
  81. }
  82. }