When passing multiple completed tasks to Task.WhenAny does Task.WhenAny give a preference to which task completed Task will be returned?
Asked
Active
Viewed 227 times
4
-
why are you sending completed tasks to `Task.WhenAny`? – Jonesopolis Aug 23 '16 at 14:18
-
No. If you're adding completed tasks, the first completed task it comes across in the collection (iterating in a natural order, nothing crazy) will be returned. I highly doubt the order is specified anywhere, so behavior *could* change, not likely though. If no tasks are completed then it'll return the first task which *does* run to completion. [Relevant source code](http://referencesource.microsoft.com#mscorlib/system/threading/Tasks/TaskFactory.cs,db51a91904616672) – Glorin Oakenfoot Aug 23 '16 at 14:34
1 Answers
2
When you want to know the exact behavior, you can often check the reference source. For instance, WhenAny
can be found here.
When looking through the source, note that the returned task is not one of your tasks, but an internally-created task (either a CompleteOnInvokePromise
instance or continuation of it), whose Result
will be one of your tasks. In the case where you are passing completed tasks into WhenAny
, the Result
is immediately set to the first completed task it encounters.

seairth
- 1,966
- 15
- 22
-
Of course, there's also a race here, assuming the non-completed tasks are hot - if you have `{t1,t2,ct1,ct2}` where the `ct` items are already completed and the `t` ones weren't at the start of the call, one of `t1` and `t2` may complete *whilst* `WhenAny` is still looping through and setting things up. In short - if you pass a mixture of incomplete and complete tasks, you're certainly not guaranteed that one of the already completed tasks will be what you get handed back. – Damien_The_Unbeliever Aug 23 '16 at 16:38