gpt4 book ai didi

c# - ValueTask 的 Task.WhenAll

转载 作者:可可西里 更新时间:2023-11-01 08:44:06 25 4
gpt4 key购买 nike

是否有接受 ValueTaskTask.WhenAll 等效项?

我可以使用

解决它
Task.WhenAll(tasks.Select(t => t.AsTask()))

如果它们都包装了一个 Task,这会很好,但是它会强制为真正的 ValueTask 分配一个 Task 对象的无用分配.

最佳答案

按照设计,没有。来自 the docs :

Methods may return an instance of this value type when it's likely that the result of their operations will be available synchronously and when the method is expected to be invoked so frequently that the cost of allocating a new Task 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>, such as to use with in methods like Task.WhenAll and Task.WhenAny, the ValueTask<TResult> would first need to be converted into a Task<TResult> using AsTask, which leads to an allocation that would have been avoided if a cached Task<TResult> had been used in the first place.

关于c# - ValueTask 的 Task.WhenAll,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45689327/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com