UnityScheduler.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using System;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4. using UnityEngine;
  5. public class UnityScheduler : MonoBehaviour
  6. {
  7. public static int MainThreadId { get; private set; }
  8. /// <summary>
  9. /// Use UpdateScheduler, LateUpdateScheduler or FixedUpdateScheduler instead.
  10. /// </summary>
  11. [Obsolete]
  12. public static UnityTaskScheduler MainThreadScheduler => UpdateScheduler;
  13. /// <summary>
  14. /// Executes tasks in the main thread, Update context.
  15. /// </summary>
  16. public static UnityTaskScheduler UpdateScheduler { get; private set; }
  17. /// <summary>
  18. /// Executes tasks in the main thread, LateUpdate context.
  19. /// </summary>
  20. public static UnityTaskScheduler LateUpdateScheduler { get; private set; }
  21. /// <summary>
  22. /// Executes tasks in the main thread, FixedUpdate context.
  23. /// </summary>
  24. public static UnityTaskScheduler FixedUpdateScheduler { get; private set; }
  25. public static UnityTaskScheduler EditorUpdateScheduler { get; private set; }
  26. /// <summary>
  27. /// Executes tasks in the thread pool. It's an alias for TaskScheduler.Default.
  28. /// </summary>
  29. public static TaskScheduler ThreadPoolScheduler => TaskScheduler.Default;
  30. [RuntimeInitializeOnLoadMethod]
  31. private static void Initialize()
  32. {
  33. MainThreadId = Thread.CurrentThread.ManagedThreadId;
  34. UpdateScheduler = new UnityTaskScheduler("Update");
  35. LateUpdateScheduler = new UnityTaskScheduler("LateUpdate");
  36. FixedUpdateScheduler = new UnityTaskScheduler("FixedUpdate");
  37. SynchronizationContext.SetSynchronizationContext(UpdateScheduler.Context);
  38. var go = new GameObject("UnityScheduler");
  39. go.hideFlags = HideFlags.HideAndDontSave;
  40. go.AddComponent<UnityScheduler>();
  41. }
  42. public static void InitializeInEditor()
  43. {
  44. MainThreadId = Thread.CurrentThread.ManagedThreadId;
  45. EditorUpdateScheduler = new UnityTaskScheduler("EditorUpdate");
  46. SynchronizationContext.SetSynchronizationContext(EditorUpdateScheduler.Context);
  47. }
  48. public static void ProcessEditorUpdate() => EditorUpdateScheduler.Activate();
  49. private void Update() => UpdateScheduler.Activate();
  50. private void LateUpdate() => LateUpdateScheduler.Activate();
  51. private void FixedUpdate() => FixedUpdateScheduler.Activate();
  52. }