Client LuaCsForBarotrauma
CrossThread.cs
1 using System.Collections.Generic;
2 using System.Threading;
3 
4 namespace Barotrauma
5 {
6  public static class CrossThread
7  {
8  public delegate void TaskDelegate();
9 
10  private sealed class Task
11  {
12  public TaskDelegate Deleg;
13  public ManualResetEvent Mre;
14  public bool Done;
15 
16  public Task(TaskDelegate d)
17  {
18  Deleg = d;
19  Mre = new ManualResetEvent(false);
20  Done = false;
21  }
22 
23  public void PerformWait()
24  {
25  if (!Done) { Mre.WaitOne(); }
26  }
27  }
28  private static readonly List<Task> enqueuedTasks;
29 
30  static CrossThread() { enqueuedTasks = new List<Task>(); }
31 
32  public static void ProcessTasks()
33  {
34  lock (enqueuedTasks)
35  {
36  foreach (var task in enqueuedTasks)
37  {
38  task.Deleg();
39  task.Mre.Set();
40  task.Done = true;
41  }
42  enqueuedTasks.Clear();
43  }
44  }
45 
46  public static void RequestExecutionOnMainThread(TaskDelegate deleg)
47  {
48  if (GameMain.MainThread == null || Thread.CurrentThread == GameMain.MainThread)
49  {
50  deleg();
51  }
52  else
53  {
54  Task newTask = new Task(deleg);
55  lock (enqueuedTasks)
56  {
57  enqueuedTasks.Add(newTask);
58  }
59  newTask.PerformWait();
60  }
61  }
62 
63  public static void AddOnMainThread<T>(this List<T> list, T element)
64  {
65  RequestExecutionOnMainThread(() => { list.Add(element); });
66  }
67 
68  public static void AddRangeOnMainThread<T>(this List<T> list, IEnumerable<T> elements)
69  {
70  RequestExecutionOnMainThread(() => { list.AddRange(elements); });
71  }
72 
73  public static void RemoveOnMainThread<T>(this List<T> list, T element)
74  {
75  RequestExecutionOnMainThread(() => { list.Remove(element); });
76  }
77 
78  public static void ClearOnMainThread<T>(this List<T> list)
79  {
80  RequestExecutionOnMainThread(() => { list.Clear(); });
81  }
82  }
83 }