UniWebViewMainThreadDispatcher.cs 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. //
  2. // UniWebViewMainThreadDispatcher.cs
  3. // Created by Wang Wei(@onevcat) on 2025-08-27.
  4. //
  5. // This file is a part of UniWebView Project (https://uniwebview.com)
  6. // By purchasing the asset, you are allowed to use this code in as many as projects
  7. // you want, only if you publish the final products under the name of the same account
  8. // used for the purchase.
  9. //
  10. // This asset and all corresponding files (such as source code) are provided on an
  11. // "as is" basis, without warranty of any kind, express of implied, including but not
  12. // limited to the warranties of merchantability, fitness for a particular purpose, and
  13. // noninfringement. In no event shall the authors or copyright holders be liable for any
  14. // claim, damages or other liability, whether in action of contract, tort or otherwise,
  15. // arising from, out of or in connection with the software or the use of other dealing in the software.
  16. //
  17. using System;
  18. using System.Collections.Generic;
  19. using UnityEngine;
  20. /// <summary>
  21. /// A main thread dispatcher for UniWebView to ensure callbacks happen on Unity's main thread.
  22. /// This is particularly important for Android where JavascriptInterface callbacks occur on JavaBridge thread.
  23. /// </summary>
  24. public class UniWebViewMainThreadDispatcher : MonoBehaviour {
  25. private static UniWebViewMainThreadDispatcher _instance;
  26. private readonly Queue<Action> _executionQueue = new Queue<Action>();
  27. private readonly object _queueLock = new object();
  28. /// <summary>
  29. /// Gets or creates the singleton instance of the main thread dispatcher.
  30. /// </summary>
  31. public static UniWebViewMainThreadDispatcher Instance {
  32. get {
  33. if (_instance == null) {
  34. // Try to find existing instance
  35. _instance = FindAnyObjectByType<UniWebViewMainThreadDispatcher>();
  36. if (_instance == null) {
  37. // Create new GameObject with dispatcher
  38. var go = new GameObject("UniWebViewMainThreadDispatcher");
  39. _instance = go.AddComponent<UniWebViewMainThreadDispatcher>();
  40. DontDestroyOnLoad(go);
  41. }
  42. }
  43. return _instance;
  44. }
  45. }
  46. void Awake() {
  47. if (_instance != null && _instance != this) {
  48. Destroy(gameObject);
  49. return;
  50. }
  51. _instance = this;
  52. DontDestroyOnLoad(gameObject);
  53. }
  54. void Update() {
  55. // Process actions queued from background threads
  56. lock (_queueLock) {
  57. while (_executionQueue.Count > 0) {
  58. var action = _executionQueue.Dequeue();
  59. try {
  60. action?.Invoke();
  61. } catch (Exception e) {
  62. UniWebViewLogger.Instance.Critical(() => $"Error executing action on main thread: {e.Message}");
  63. }
  64. }
  65. }
  66. }
  67. /// <summary>
  68. /// Enqueues an action to be executed on the main thread.
  69. /// </summary>
  70. /// <param name="action">The action to execute on the main thread</param>
  71. public void Enqueue(Action action) {
  72. if (action == null) {
  73. return;
  74. }
  75. lock (_queueLock) {
  76. _executionQueue.Enqueue(action);
  77. }
  78. }
  79. /// <summary>
  80. /// Executes a function on the main thread and returns the result.
  81. /// This method blocks until the function completes.
  82. /// </summary>
  83. /// <typeparam name="T">Return type of the function</typeparam>
  84. /// <param name="func">The function to execute</param>
  85. /// <param name="timeoutSeconds">Timeout in seconds (default: 5)</param>
  86. /// <returns>The result of the function</returns>
  87. public T ExecuteOnMainThread<T>(Func<T> func, float timeoutSeconds = 5f) {
  88. if (func == null) {
  89. return default(T);
  90. }
  91. // If we're already on the main thread, execute directly
  92. if (IsMainThread()) {
  93. return func();
  94. }
  95. T result = default(T);
  96. bool completed = false;
  97. Exception exception = null;
  98. Enqueue(() => {
  99. try {
  100. result = func();
  101. } catch (Exception e) {
  102. exception = e;
  103. } finally {
  104. completed = true;
  105. }
  106. });
  107. // Wait for completion with timeout using thread-safe DateTime
  108. var startTime = System.DateTime.Now;
  109. while (!completed) {
  110. if ((System.DateTime.Now - startTime).TotalSeconds > timeoutSeconds) {
  111. UniWebViewLogger.Instance.Critical(() => $"Main thread execution timeout after {timeoutSeconds} seconds");
  112. break;
  113. }
  114. System.Threading.Thread.Sleep(1);
  115. }
  116. if (exception != null) {
  117. throw exception;
  118. }
  119. return result;
  120. }
  121. /// <summary>
  122. /// Checks if the current thread is Unity's main thread.
  123. /// This is a heuristic based on thread ID, which works for most cases.
  124. /// </summary>
  125. private static bool IsMainThread() {
  126. // Unity's main thread typically has ID 1, but this is not guaranteed
  127. // A more robust check would require platform-specific code
  128. return System.Threading.Thread.CurrentThread.ManagedThreadId == 1;
  129. }
  130. void OnDestroy() {
  131. if (_instance == this) {
  132. _instance = null;
  133. }
  134. }
  135. }