Why would one use Task over ValueTask in C#?

后端 未结 4 468
情歌与酒
情歌与酒 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:07

    However I still do not understand what is the problem with using ValueTask always

    Struct types are not free. Copying structs that are larger than the size of a reference can be slower than copying a reference. Storing structs that are larger than a reference takes more memory than storing a reference. Structs that are larger than 64 bits might not be enregistered when a reference could be enregistered. The benefits of lower collection pressure may not exceed the costs.

    Performance problems should be approached with an engineering discipline. Make goals, measure your progress against goals, and then decide how to modify the program if goals are not met, measuring along the way to make sure that your changes are actually improvements.

    why async/await wasn't built with a value type from the start.

    await was added to C# long after the Task type already existed. It would have been somewhat perverse to invent a new type when one already existed. And await went through a great many design iterations before settling on the one that was shipped in 2012. The perfect is the enemy of the good; better to ship a solution that works well with the existing infrastructure and then if there is user demand, provide improvements later.

    I note also that the new feature of allowing user-supplied types to be the output of a compiler-generated method adds considerable risk and testing burden. When the only things you can return are void or a task, the testing team does not have to consider any scenario in which some absolutely crazy type is returned. Testing a compiler means figuring out not just what programs people are likely to write, but what programs are possible to write, because we want the compiler to compile all legal programs, not just all sensible programs. That's expensive.

    Can someone explain when ValueTask would fail to do the job?

    The purpose of the thing is improved performance. It doesn't do the job if it doesn't measurably and significantly improve performance. There is no guarantee that it will.

提交回复
热议问题