-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainThreadDispatcher.cs
More file actions
63 lines (58 loc) · 1.83 KB
/
Copy pathMainThreadDispatcher.cs
File metadata and controls
63 lines (58 loc) · 1.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
using System;
using System.Collections.Generic;
using UnityEngine;
namespace ModUpdater
{
/// <summary>
/// Attach this MonoBehaviour to a persistent GameObject so that
/// background threads can queue work onto Unity's main thread.
/// </summary>
public class MainThreadDispatcher : MonoBehaviour
{
private static MainThreadDispatcher instance;
private static readonly Queue<Action> queue = new Queue<Action>();
private static readonly object lockObj = new object();
/// <summary>
/// Lazily creates a hidden, DontDestroyOnLoad GameObject
/// the first time anything needs to dispatch.
/// </summary>
public static void Initialise()
{
if (instance != null) return;
var go = new GameObject("[ModUpdater_Dispatcher]");
DontDestroyOnLoad(go);
go.hideFlags = HideFlags.HideAndDontSave;
instance = go.AddComponent<MainThreadDispatcher>();
}
/// <summary>
/// Enqueue an action to run on the next Update() frame.
/// Safe to call from any thread.
/// </summary>
public static void Enqueue(Action action)
{
if (action == null) return;
lock (lockObj)
{
queue.Enqueue(action);
}
}
private void Update()
{
lock (lockObj)
{
while (queue.Count > 0)
{
Action action = queue.Dequeue();
try
{
action.Invoke();
}
catch (Exception ex)
{
Debug.LogError($"[ModUpdater] Dispatcher error: {ex}");
}
}
}
}
}
}