Why would one use Task over ValueTask in C#?

后端 未结 4 471
情歌与酒
情歌与酒 2020-12-04 05:27

As of C# 7.0 async methods can return ValueTask. The explanation says that it should be used when we have a cached result or simulating async via synchronous code. How

4条回答
  •  执念已碎
    2020-12-04 06:23

    From the API docs (emphasis added):

    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.

    There are tradeoffs to using a ValueTask instead of a Task. For example, while a ValueTask can help avoid an allocation in the case where the successful result is available synchronously, it also contains two fields whereas a Task as a reference type is a single field. This means that a method call ends up returning two fields worth of data instead of one, which is more data to copy. It also means that if a method that returns one of these is awaited within an async method, the state machine for that async method will be larger due to needing to store the struct that's two fields instead of a single reference.

    Further, for uses other than consuming the result of an asynchronous operation via await, ValueTask can lead to a more convoluted programming model, which can in turn actually lead to more allocations. For example, consider a method that could return either a Task with a cached task as a common result or a ValueTask. If the consumer of the result wants to use it as a Task, such as to use with in methods like Task.WhenAll and Task.WhenAny, the ValueTask would first need to be converted into a Task using AsTask, which leads to an allocation that would have been avoided if a cached Task had been used in the first place.

    As such, the default choice for any asynchronous method should be to return a Task or Task. Only if performance analysis proves it worthwhile should a ValueTask be used instead of Task.

提交回复
热议问题