How should I convert a function returning a non-generic Task to ValueTask?

杀马特。学长 韩版系。学妹 提交于 2021-02-20 06:30:52

问题


I'm working on some code which builds a buffer in memory and then empties it into a TextWriter when the buffer fills up. Most of the time, the character will go straight into the buffer (synchronously) but occasionally (once every 4kb) I need to call TextWriter.WriteAsync.

In the System.Threading.Tasks.Extensions package there only appears to be a ValueTask<T> struct, and no non-generic ValueTask (without a type parameter). Why is there no ValueTask, and what should I do if I need to convert a method returning a non-generic Task (that is, the async equivalent of a void method) to ValueTask?


回答1:


Shot in the dark, but I think it's because Task.CompletedTask is sufficient for most non-generic cases.

One way to think of ValueTask<T> is as a union of Task<T> and T (for asynchronous and synchronous cases respectively). Accordingly a non-generic ValueTask would be a union of Task and... nothing, so just a Task.

I can't think of a case where a non-generic ValueTask would be practically different than caching an already completed Task (which is what Task.CompletedTask is), though I'd love to learn about any.



来源:https://stackoverflow.com/questions/48935667/how-should-i-convert-a-function-returning-a-non-generic-task-to-valuetask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!