WaitForFirstN Tasks Method

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);
      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];

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));
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.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s