Is there a way in the new async dotnet 4.5 library to set a timeout on the Task.WhenAll
method. I want to fetch several sources and stop after say 5 seconds and
I think a clearer, more robust option that also does exception handling right would be to use Task.WhenAny on each task together with a timeout task, go through all the completed tasks and filter out the timeout ones, and use await Task.WhenAll()
instead of Task.Result
to gather all the results.
Here's a complete working solution:
static async Task WhenAll(IEnumerable> tasks, TimeSpan timeout)
{
var timeoutTask = Task.Delay(timeout).ContinueWith(_ => default(TResult));
var completedTasks =
(await Task.WhenAll(tasks.Select(task => Task.WhenAny(task, timeoutTask)))).
Where(task => task != timeoutTask);
return await Task.WhenAll(completedTasks);
}