ThreadingHelper.cs 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. using System;
  2. using System.ComponentModel;
  3. using System.Linq;
  4. using System.Threading;
  5. using BepInEx.Logging;
  6. using UnityEngine;
  7. namespace BepInEx
  8. {
  9. /// <summary>
  10. /// Provides methods for running code on other threads and synchronizing with the main thread.
  11. /// </summary>
  12. public sealed class ThreadingHelper : MonoBehaviour, ISynchronizeInvoke
  13. {
  14. private readonly object _invokeLock = new object();
  15. private Action _invokeList;
  16. private Thread _mainThread;
  17. /// <summary>
  18. /// Current instance of the helper.
  19. /// </summary>
  20. public static ThreadingHelper Instance { get; private set; }
  21. /// <summary>
  22. /// Gives methods for invoking delegates on the main unity thread, both synchronously and asynchronously.
  23. /// Can be used in many built-in framework types, for example <see cref="System.IO.FileSystemWatcher.SynchronizingObject"/>
  24. /// and <see cref="System.Timers.Timer.SynchronizingObject"/> to make their events fire on the main unity thread.
  25. /// </summary>
  26. public static ISynchronizeInvoke SynchronizingObject => Instance;
  27. internal static void Initialize()
  28. {
  29. var go = new GameObject("BepInEx_ThreadingHelper");
  30. DontDestroyOnLoad(go);
  31. Instance = go.AddComponent<ThreadingHelper>();
  32. }
  33. /// <summary>
  34. /// Queue the delegate to be invoked on the main unity thread. Use to synchronize your threads.
  35. /// </summary>
  36. public void StartSyncInvoke(Action action)
  37. {
  38. if (action == null) throw new ArgumentNullException(nameof(action));
  39. lock (_invokeLock) _invokeList += action;
  40. }
  41. private void Update()
  42. {
  43. if (_mainThread == null)
  44. _mainThread = Thread.CurrentThread;
  45. // Safe to do outside of lock because nothing can remove callbacks, at worst we execute with 1 frame delay
  46. if (_invokeList == null) return;
  47. Action toRun;
  48. lock (_invokeLock)
  49. {
  50. toRun = _invokeList;
  51. _invokeList = null;
  52. }
  53. // Need to execute outside of the lock in case the callback itself calls Invoke we could deadlock
  54. // The invocation would also block any threads that call Invoke
  55. foreach (var action in toRun.GetInvocationList().Cast<Action>())
  56. {
  57. try
  58. {
  59. action();
  60. }
  61. catch (Exception ex)
  62. {
  63. LogInvocationException(ex);
  64. }
  65. }
  66. }
  67. /// <summary>
  68. /// Queue the delegate to be invoked on a background thread. Use this to run slow tasks without affecting the game.
  69. /// NOTE: Most of Unity API can not be accessed while running on another thread!
  70. /// </summary>
  71. /// <param name="action">
  72. /// Task to be executed on another thread. Can optionally return an Action that will be executed on the main thread.
  73. /// You can use this action to return results of your work safely. Return null if this is not needed.
  74. /// </param>
  75. public void StartAsyncInvoke(Func<Action> action)
  76. {
  77. void DoWork(object _)
  78. {
  79. try
  80. {
  81. var result = action();
  82. if (result != null)
  83. StartSyncInvoke(result);
  84. }
  85. catch (Exception ex)
  86. {
  87. LogInvocationException(ex);
  88. }
  89. }
  90. if (!ThreadPool.QueueUserWorkItem(DoWork))
  91. throw new NotSupportedException("Failed to queue the action on ThreadPool");
  92. }
  93. private static void LogInvocationException(Exception ex)
  94. {
  95. Logging.Logger.Log(LogLevel.Error, ex);
  96. if (ex.InnerException != null) Logging.Logger.Log(LogLevel.Error, "INNER: " + ex.InnerException);
  97. }
  98. #region ISynchronizeInvoke
  99. IAsyncResult ISynchronizeInvoke.BeginInvoke(Delegate method, object[] args)
  100. {
  101. object Invoke()
  102. {
  103. try { return method.DynamicInvoke(args); }
  104. catch (Exception ex) { return ex; }
  105. }
  106. var result = new InvokeResult();
  107. if (!InvokeRequired)
  108. result.Finish(Invoke(), true);
  109. else
  110. StartSyncInvoke(() => result.Finish(Invoke(), false));
  111. return result;
  112. }
  113. object ISynchronizeInvoke.EndInvoke(IAsyncResult result)
  114. {
  115. result.AsyncWaitHandle.WaitOne();
  116. if (result.AsyncState is Exception ex)
  117. throw ex;
  118. return result.AsyncState;
  119. }
  120. object ISynchronizeInvoke.Invoke(Delegate method, object[] args)
  121. {
  122. var invokeResult = ((ISynchronizeInvoke)this).BeginInvoke(method, args);
  123. return ((ISynchronizeInvoke)this).EndInvoke(invokeResult);
  124. }
  125. /// <summary>
  126. /// False if current code is executing on the main unity thread, otherwise True.
  127. /// Warning: Will return false before the first frame finishes (i.e. inside plugin Awake and Start methods).
  128. /// </summary>
  129. /// <inheritdoc />
  130. public bool InvokeRequired => _mainThread == null || _mainThread != Thread.CurrentThread;
  131. private sealed class InvokeResult : IAsyncResult
  132. {
  133. public InvokeResult()
  134. {
  135. AsyncWaitHandle = new EventWaitHandle(false, EventResetMode.ManualReset);
  136. }
  137. public void Finish(object result, bool completedSynchronously)
  138. {
  139. AsyncState = result;
  140. CompletedSynchronously = completedSynchronously;
  141. IsCompleted = true;
  142. ((EventWaitHandle)AsyncWaitHandle).Set();
  143. }
  144. public bool IsCompleted { get; private set; }
  145. public WaitHandle AsyncWaitHandle { get; }
  146. public object AsyncState { get; private set; }
  147. public bool CompletedSynchronously { get; private set; }
  148. }
  149. #endregion
  150. }
  151. }