using System; using System.Threading.Tasks; using System.Collections.Generic; namespace Cobilas.Threading.Tasks { #pragma warning disable CS1591 // O comentário XML ausente não foi encontrado para o tipo ou membro visível publicamente public static class TaskPool { #pragma warning restore CS1591 // O comentário XML ausente não foi encontrado para o tipo ou membro visível publicamente private readonly static List tasksList = new List(); /// Returns the number of allocated tasks. public static int Count => tasksList.Count; /// The number of tasks that are already vacant. public static int VacantTaskCount { get { int res = byte.MaxValue; for (int I = 0; I < Count; I++) if (tasksList[I].IsFaulted || tasksList[I].IsCompleted || tasksList[I].IsCanceled) res++; return res; } } /// The number of tasks that are not vacant. public static int NonVacantTaskCount => Count - VacantTaskCount; /// The number of tasks that are not vacant. public static void InitTask(Action action, out Task task) { int taskIndex = GetVacantTask(); if (taskIndex >= 0) { task = tasksList[taskIndex] = tasksList[taskIndex].ContinueWith(ct => { ct.Dispose(); action(); }); } else tasksList.Add(task = Task.Run(action)); } /// The number of tasks that are not vacant. public static void InitTask(Action action) => InitTask(action, out _); /// The number of tasks that are not vacant. public static void InitTask(Func func, out Task res) { int taskIndex = GetVacantTask(); if (taskIndex >= 0) { tasksList[taskIndex] = tasksList[taskIndex].ContinueWith(ct => { ct.Dispose(); return func(); }); res = (Task)tasksList[taskIndex]; } else tasksList.Add(res = Task.Run(func)); } /// The number of tasks that are not vacant. public static void InitTask(Func func) => InitTask(func, out _); private static int GetVacantTask() { for (int I = 0; I < Count; I++) if (tasksList[I].IsFaulted || tasksList[I].IsCompleted || tasksList[I].IsCanceled) return I; return -1; } } }