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 skip the sources that weren't finished.
WhenAll returns control after all tasks are completed, while WhenAny returns control as soon as a single task is completed.
WhenAll creates a task that will complete when all of the supplied tasks have been completed. It's pretty straightforward what this method does, it simply receives a list of Tasks and returns a Task when all of the received Tasks completes.
The Task. WaitAll blocks the current thread until all other tasks have completed execution. The Task. WhenAll method is used to create a task that will complete if and only if all the other tasks have completed.
WhenAll(Task[]) Creates a task that will complete when all of the Task objects in an array have completed. WhenAll<TResult>(IEnumerable<Task<TResult>>) Creates a task that will complete when all of the Task<TResult> objects in an enumerable collection have completed.
You could combine the resulting Task
with a Task.Delay()
using Task.WhenAny()
:
await Task.WhenAny(Task.WhenAll(tasks), Task.Delay(timeout));
If you want to harvest completed tasks in case of a timeout:
var completedResults = tasks .Where(t => t.Status == TaskStatus.RanToCompletion) .Select(t => t.Result) .ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With