-
Notifications
You must be signed in to change notification settings - Fork 1
/
UnityDispatcher.cs
86 lines (76 loc) · 2.54 KB
/
UnityDispatcher.cs
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
using System;
using System.Collections.Generic;
using UnityEngine;
namespace Microsoft.Unity
{
/// <summary>
/// A helper class for dispatching actions to run on various Unity threads.
/// </summary>
public class UnityDispatcher : MonoBehaviour
{
#region Member Variables
static private UnityDispatcher instance;
static private Queue<Action> queue = new Queue<Action>(8);
static private volatile bool queued = false;
#endregion // Member Variables
#region Internal Methods
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
static private void Initialize()
{
lock (queue)
{
if (instance == null)
{
instance = new GameObject("Dispatcher").AddComponent<UnityDispatcher>();
DontDestroyOnLoad(instance.gameObject);
}
}
}
#endregion // Internal Methods
#region Unity Overrides
protected virtual void Update()
{
// Action placeholder
Action action = null;
// Do this as long as there's something in the queue
while (queued)
{
// Lock only long enough to take an item
lock (queue)
{
// Get the next action
action = queue.Dequeue();
// Have we exhausted the queue?
if (queue.Count == 0) { queued = false; }
}
// Execute the action outside of the lock
action();
}
}
#endregion // Unity Overrides
#region Public Methods
/// <summary>
/// Schedules the specified action to be run on Unity's main thread.
/// </summary>
/// <param name="action">
/// The action to run.
/// </param>
static public void InvokeOnAppThread(Action action)
{
// Validate
if (action == null) throw new ArgumentNullException(nameof(action));
// Lock to be thread-safe
lock (queue)
{
// Add the action
queue.Enqueue(action);
// Action is in the queue
queued = true;
}
}
#endregion // Public Methods
}
// #endif // Not using UWP-specific version anymore
}