Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asynchronous Task.WhenAll with timeout

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.

like image 324
broersa Avatar asked Mar 23 '12 21:03

broersa


People also ask

Can you tell difference between task WhenAll and task WhenAny?

WhenAll returns control after all tasks are completed, while WhenAny returns control as soon as a single task is completed.

Does task WhenAll start the tasks?

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.

What is the difference between task WaitAll and task WhenAll?

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.

What is task WhenAll?

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.


1 Answers

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(); 
like image 95
svick Avatar answered Sep 27 '22 20:09

svick