cs-codex-dist-tests/Tests/CodexContinuousTests/TaskFactory.cs

52 lines
1.3 KiB
C#
Raw Normal View History

2023-06-28 14:19:37 +00:00
namespace ContinuousTests
{
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);
}
}
}
}