Why would one use Task over ValueTask in C#?

后端 未结 4 455
情歌与酒
情歌与酒 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 05:59

    There is some changes in .Net Core 2.1. Starting from .net core 2.1 ValueTask can represent not only the synchronous completed actions but the async completed too. In addition we receive non-generic ValueTask type.

    I will leave Stephen Toub comment which is related to your question:

    We still need to formalize guidance, but I expect it'll be something like this for public API surface area:

    • Task provides the most usability.

    • ValueTask provides the most options for performance optimization.

    • If you're writing an interface / virtual method that others will override, ValueTask is the right default choice.

    • If you expect the API to be used on hot paths where allocations will matter, ValueTask is a good choice.

    • Otherwise, where performance isn't critical, default to Task, as it provides better guarantees and usability.

    From an implementation perspective, many of the returned ValueTask instances will still be backed by Task.

    Feature can be used not only in the .net core 2.1. You will be able to use it with System.Threading.Tasks.Extensions package.

提交回复
热议问题