1 using System.Collections.Generic;
2 using System.Threading;
6 public static class CrossThread
8 public delegate
void TaskDelegate();
10 private sealed
class Task
12 public TaskDelegate Deleg;
13 public ManualResetEvent Mre;
16 public Task(TaskDelegate d)
19 Mre =
new ManualResetEvent(
false);
23 public void PerformWait()
25 if (!Done) { Mre.WaitOne(); }
28 private static readonly List<Task> enqueuedTasks;
30 static CrossThread() { enqueuedTasks =
new List<Task>(); }
32 public static void ProcessTasks()
36 foreach (var task
in enqueuedTasks)
42 enqueuedTasks.Clear();
46 public static void RequestExecutionOnMainThread(TaskDelegate deleg)
48 if (GameMain.MainThread ==
null || Thread.CurrentThread == GameMain.MainThread)
54 Task newTask =
new Task(deleg);
57 enqueuedTasks.Add(newTask);
59 newTask.PerformWait();
63 public static void AddOnMainThread<T>(
this List<T> list, T element)
65 RequestExecutionOnMainThread(() => { list.Add(element); });
68 public static void AddRangeOnMainThread<T>(
this List<T> list, IEnumerable<T> elements)
70 RequestExecutionOnMainThread(() => { list.AddRange(elements); });
73 public static void RemoveOnMainThread<T>(
this List<T> list, T element)
75 RequestExecutionOnMainThread(() => { list.Remove(element); });
78 public static void ClearOnMainThread<T>(
this List<T> list)
80 RequestExecutionOnMainThread(() => { list.Clear(); });