2

When waiting synchronously an array of tasks to complete with the Task.WaitAll method, it is possible to specify a timeout in milliseconds. When the timeout is reached WaitAll stops waiting and returns false.

I would like to know if there is a way to get a sublist of the tasks that did not reach completion after the timeout.

Chedy2149
  • 2,821
  • 4
  • 33
  • 56
  • 6
    `tasks.Where(t => !t.IsCompleted)`? Note that there is always an inherent race condition between a timeout and checking the results of the timeout, so `WaitAll` having dedicated code to return the tasks that did not complete would not be better than checking it after the fact. – Jeroen Mostert Jul 19 '18 at 09:03
  • look at this post https://stackoverflow.com/questions/4238345/asynchronously-wait-for-taskt-to-complete-with-timeout – Amine Ramoul Jul 19 '18 at 09:05

1 Answers1

2

As suggested by Jeroen Mostert in the comments, when Task.WaitAll returns false after the timeout we can filter for the completed tasks.

Example:

var tasks = new task[] 
{
    Task.Run(someMethod),
    Task.Run(someMethod1),
    Task.Run(someMethod2),
    Task.Run(someMethod3),
};

bool allTasksAreCompleted = Task.WaitAll(tasks, 10000);

if (!allTasksAreCompleted)
{
    var incompleteTasks = tasks.Where(t => !t.IsCompleted);
}

If Task.WaitAll times out, we will get the incomplete tasks in the incompleteTasks variable.

Chedy2149
  • 2,821
  • 4
  • 33
  • 56