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 资料的方法
What you describe seems like a very common demand however I could not find anywhere an example of this. And I searched a lot... I finally created the following:
I assume here a method SomeTaskAsync that returns Task<MyResult>.
From the members of completedTasks, only tasks of type MyResult are our own tasks that managed to beat the clock. Task.Delay returns a different type. This requires some compromise on typing, but still works beautifully and quite simple.
(The array can of course be built dynamically using a query + ToArray).
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 useawait Task.WhenAll()
instead ofTask.Result
to gather all the results.Here's a complete working solution:
Seems like the Task.WaitAll overload with the timeout parameter is all you need - if it returns true, then you know they all completed - otherwise, you can filter on IsCompleted.
I came to the following piece of code that does what I needed:
My explanation is in my blogpost: http://blog.bekijkhet.com/2012/03/c-async-examples-whenall-whenany.html
In addition to timeout, I also check the cancellation which is useful if you are building a web app.