如何将返回非泛型Task的函数转换为ValueTask? [英] How should I convert a function returning a non-generic Task to ValueTask?
问题描述
我正在研究一些代码,该代码在内存中建立一个缓冲区,然后在缓冲区填满时将其清空为 TextWriter
.大多数情况下,角色会(同步)直接进入缓冲区,但偶尔(每4kb一次)我需要调用 TextWriter.WriteAsync
.
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
.
在 System.Threading.Tasks.Extensions
中包中似乎只有一个 ValueTask< T>
结构,并且没有非通用的 ValueTask
(无类型参数).为什么没有 ValueTask
,以及如果我需要转换返回非通用 Task
(即,与void
方法)添加到 ValueTask
?
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
?
推荐答案
Shot in the dark, but I think it's because Task.CompletedTask
is sufficient for most non-generic cases.
想到 ValueTask< T>
的一种方法是将 Task< T>
和 T
结合起来(对于异步和同步情况分别).因此,非通用的 ValueTask
将是 Task
的联合,并且……什么都没有,所以只是一个 Task
.
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
.
我想不出非通用的 ValueTask
与缓存已完成的 Task
(这是 Task)实际上不同的情况.CompletedTask
是),尽管我很想学习任何内容.
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.
这篇关于如何将返回非泛型Task的函数转换为ValueTask?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!