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.
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Generic Generics in Managed C++
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
You could combine the resulting
Task
with aTask.Delay()
usingTask.WhenAny()
:If you want to harvest completed tasks in case of a timeout:
Check out the "Early Bailout" and "Task.Delay" sections from Microsoft's Task-Based Asynchronous Pattern Overview.
void result version of @i3arnon 's answer, along with comments and changing first argument to use extension this.
I've also got a forwarding method specifying timeout as an int using
TimeSpan.FromMilliseconds(millisecondsTimeout)
to match other Task methods.Check out a custom task combinator proposed in http://tutorials.csharp-online.net/Task_Combinators
I have not tried it yet.
In addition to svick's answer, the following works for me when I have to wait for a couple of tasks to complete but have to process something else while I'm waiting:
You can use the following code:
How it works:
You need to put in the timeoutTime variable the limit of time for all tasks to be completed. So basically all tasks will wait in maximum the time that you set in timeoutTime. When all the tasks return the result, the timeout will not occur and the tasksResult will be set.
After that we are only getting the completed tasks. The tasks that were not completed will have no results.