2 using System.Collections.Generic;
5 using System.Threading.Tasks;
9 public static class TaskPool
11 const int MaxTasks = 5000;
13 private struct TaskAction
17 public Action<Task, object> OnCompletion;
18 public object UserData;
21 private static readonly List<TaskAction> taskActions =
new List<TaskAction>();
23 public static void ListTasks()
27 DebugConsole.NewMessage($
"Task count: {taskActions.Count}");
28 for (
int i = 0; i < taskActions.Count; i++)
30 DebugConsole.NewMessage($
" -{i}: {taskActions[i].Name}, {taskActions[i].Task.Status}");
35 public static bool IsTaskRunning(
string name)
39 return taskActions.Any(t => t.Name == name);
43 private static void AddInternal(
string name, Task task, Action<Task, object> onCompletion,
object userdata,
bool addIfFound =
true)
49 if (taskActions.Any(t => t.Name == name)) {
return; }
51 if (taskActions.Count >= MaxTasks)
54 "Too many tasks in the TaskPool:\n" +
string.Join(
'\n', taskActions.Select(ta => ta.Name))
57 taskActions.Add(
new TaskAction() { Name = name, Task = task, OnCompletion = onCompletion, UserData = userdata });
58 DebugConsole.Log($
"New task: {name} ({taskActions.Count}/{MaxTasks})");
62 public static void Add(
string name, Task task, Action<Task> onCompletion)
64 AddInternal(name, task, (Task t,
object obj) => { onCompletion?.Invoke(t); },
null);
66 public static void AddIfNotFound(
string name, Task task, Action<Task> onCompletion)
68 AddInternal(name, task, (Task t,
object obj) => { onCompletion?.Invoke(t); },
null, addIfFound:
false);
71 public static void Add<U>(
string name, Task task, U userdata, Action<Task, U> onCompletion) where U :
class
73 AddInternal(name, task, (Task t,
object obj) => { onCompletion?.Invoke(t, (U)obj); }, userdata);
76 public static void Update()
80 for (
int i = 0; i < taskActions.Count; i++)
82 if (taskActions[i].Task.IsCompleted)
84 taskActions[i].OnCompletion?.Invoke(taskActions[i].Task, taskActions[i].UserData);
85 DebugConsole.Log($
"Task {taskActions[i].Name} completed ({taskActions.Count-1}/{MaxTasks})");
86 taskActions.RemoveAt(i);
93 public static void PrintTaskExceptions(Task task,
string msg)
95 DebugConsole.ThrowError(msg);
96 foreach (Exception e
in task.Exception.InnerExceptions)
98 DebugConsole.ThrowError(e.Message +
"\n" + e.StackTrace.CleanupStackTrace());