diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c6bb293 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +*.meta diff --git a/UnityMainThreadDispatcher.cs b/UnityMainThreadDispatcher.cs index 3b40ca9..9101602 100644 --- a/UnityMainThreadDispatcher.cs +++ b/UnityMainThreadDispatcher.cs @@ -29,12 +29,18 @@ public class UnityMainThreadDispatcher : MonoBehaviour { private static readonly Queue _executionQueue = new Queue(); public void Update() { - lock(_executionQueue) { - while (_executionQueue.Count > 0) { - _executionQueue.Dequeue().Invoke(); - } - } - } + // Make local copy to avoid holding the lock while the actions execute. + Queue queueCopy; + lock (_executionQueue) + { + queueCopy = new Queue(_executionQueue); + _executionQueue.Clear(); + } + while (queueCopy.Count > 0) + { + queueCopy.Dequeue().Invoke(); + } + } /// /// Locks the queue and adds the IEnumerator to the queue