Search code examples
c#task-parallel-libraryvaluetask

Task.WhenAll for ValueTask


Is there an equivalent of Task.WhenAll accepting ValueTask?

I can work around it using

Task.WhenAll(tasks.Select(t => t.AsTask()))

This will be fine if they're all wrapping a Task but it will force the useless allocation of a Task object for real ValueTask.


Solution

  • By design, no. From the docs: (link updated)

    A method may return an instance of this value type when it's likely that the result of its operation will be available synchronously, and when it's expected to be invoked so frequently that the cost of allocating a new Task<TResult> for each call will be prohibitive.

    For example, consider a method that could return either a Task<TResult> with a cached task as a common result or a ValueTask<TResult>. If the consumer of the result wants to use it as a Task<TResult> in a method like WhenAll or WhenAny, the ValueTask<TResult> must first be converted to a Task<TResult> using AsTask(), leading to an allocation that would have been avoided if a cached Task<TResult> had been used in the first place.