There is a definite gap between TAP Utilities Task.WaitAny and Task.WaitAll. How do we wait for the first ‘N’ tasks from an array of tasks. That is one utility that is missing from TAP’s rich repository. It might not be hard to implement one by yourself though.
public static int[] WaitForFirstN(this System.Threading.Tasks.Task[] tasks,int numberOfTasks) { if (numberOfTasks > tasks.Length) throw new ArgumentOutOfRangeException(); var _taskDictionary = Enumerable.Range(0, tasks.Length).ToDictionary(x => tasks[x]); List<int> completedTaskIndices = new List<int>(); while (completedTaskIndices.Count < numberOfTasks) { var index = System.Threading.Tasks.Task.WaitAny(tasks); completedTaskIndices.Add(_taskDictionary[tasks[index]]); tasks = tasks.Where(x => x.Id != tasks[index].Id).ToArray(); } return completedTaskIndices.ToArray(); }
The above code uses existing Task Collaborators Task.WaitAny to wait for ‘N’ tasks specified by numberOfTasks parameter. Let’s try the following in code.
System.Threading.Tasks.Task[] tasks = new System.Threading.Tasks.Task[5]; [TestInitialize] public void Init() { for (int ctr = 0; ctr <= 4; ctr++) { int factor = ctr; tasks[ctr] = System.Threading.Tasks.Task.Run(() => Thread.Sleep(factor * 250 + 50)); } } [TestMethod] public void WaitForFirstN_ValidResult_EqualsExpected() { var completedTaskList = tasks.WaitForFirstN(3); CollectionAssert.AreEqual(new int[] { 0, 1, 2 }, completedTaskList); }
Code shown in this sample can also be on my GitHub.
One interesting though. Curious why Framework doesn’t allow us to create Static Extension Methods for types.