假设您想编写一个类似于以下方法的方法。它包装了一个返回 ValueTask<T>
的函数使用简单的性能监控代码:
static async Task Measure<T>(Func<ValueTask<T>> body)
{
Console.WriteLine($"Starting perf test");
var sw = Stopwatch.StartNew();
await body();
sw.Stop();
Console.WriteLine(sw.Elapsed);
}
我的问题是:有没有办法把这个函数写一次,让它可以接收Func<ValueTask<T>>
和 Func<Task<T>>
?
当然,您可以简单地复制代码并仅更改参数的类型。
static async Task Measure<T>(Func<Task<T>> body) { ... }
实现将完全相同。我问自己在处理 ValueTask
时是否可以避免这种代码重复和 Task
.到现在为止,我想不出一个好的解决方案。有什么想法吗?
最佳答案
根据官方文档:Generalized async return types
The
ValueTask
struct has a constructor with aTask
parameter so that you can construct aValueTask
from the return value of any existing async method:
这意味着您可以编写一个重载来包装 body
并仅调用一个完成工作的方法
static Task Measure<T>(Func<Task<T>> body)
{
var wrapped = () => new ValueTask<T>( body() );
return Measure( wrapped );
}
static async Task Measure<T>(Func<ValueTask<T>> body)
{
Console.WriteLine($"Starting perf test");
var sw = Stopwatch.StartNew();
await body();
sw.Stop();
Console.WriteLine(sw.Elapsed);
}
关于c# - 如何编写一个可以处理 Task 和 ValueTask 的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43890361/