c# - 如何编写一个可以处理 Task 和 ValueTask 的方法?

标签 c# c#-7.0

假设您想编写一个类似于以下方法的方法。它包装了一个返回 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 a Task parameter so that you can construct a ValueTask 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/

相关文章:

c# - 单元测试静态实用程序类

.net - C# 7 : Why is tuple deconstruction not implemented through an interface?

null - 我应该使用 == 或 'is' 来检查 C# 7 中的 null 吗?

c# - 编码的 UI 测试现在收到有关未找到 Newtonsoft.json 的错误

c# - LocalReport.SetParameters Exception 试图设置此报告中未定义的报告参数 'ParameterName'

c# - 空传播功能和 Razor View

c# - 在方法中创建结构时,引用返回不起作用

c# - Serilog Destructure.ByTransforming<Interface>() 不工作

c# - 将 Asp.Net Mvc、Web Api 应用程序发布到 Windows Azure