2023-12-20 14:56:03 +00:00
|
|
|
|
namespace Utils
|
2023-06-28 14:19:37 +00:00
|
|
|
|
{
|
|
|
|
|
public class TaskFactory
|
|
|
|
|
{
|
|
|
|
|
private readonly object taskLock = new();
|
|
|
|
|
private readonly List<Task> activeTasks = new List<Task>();
|
|
|
|
|
|
2023-11-14 12:28:50 +00:00
|
|
|
|
public void Run(Action action, string name)
|
2023-06-28 14:19:37 +00:00
|
|
|
|
{
|
|
|
|
|
lock (taskLock)
|
|
|
|
|
{
|
2023-11-14 12:28:50 +00:00
|
|
|
|
activeTasks.Add(Task.Run(() => CatchException(action, name)).ContinueWith(CleanupTask, null));
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private void CatchException(Action action, string name)
|
|
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
action();
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
|
|
|
|
Console.WriteLine($"Exception in task '{name}': " + ex);
|
2023-06-28 14:19:37 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public void WaitAll()
|
|
|
|
|
{
|
|
|
|
|
var tasks = activeTasks.ToArray();
|
|
|
|
|
Task.WaitAll(tasks);
|
|
|
|
|
|
|
|
|
|
var moreTasks = false;
|
|
|
|
|
lock (taskLock)
|
|
|
|
|
{
|
|
|
|
|
activeTasks.RemoveAll(task => task.IsCompleted);
|
|
|
|
|
moreTasks = activeTasks.Any();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (moreTasks) WaitAll();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private void CleanupTask(Task completedTask, object? arg)
|
|
|
|
|
{
|
|
|
|
|
lock (taskLock)
|
|
|
|
|
{
|
|
|
|
|
activeTasks.Remove(completedTask);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|