首页 > 解决方案 > 将语句作为 Func 发送的正确方法

问题描述

我制作了一个小型基准测试库,它接收Func<Task>对象,运行它们一定次数,并使用一个Stopwatch对象来计算运行所需的平均时间:

public static async Task<BenchmarkResults> BenchmarkAsync(Func<Task> action, int repetitions, bool singleCore)
{
    // Run func, time it each time, compute average, return results.
}

IBenchmark用一种方法制作了一个小界面Run()。我目前使用这个库的方式是制作实现IBenchmark并传递调用该Run​​方法的 lambda 的基准类。这些IBenchmark对象通过扩展方法添加到 DI:

var results = AsyncBenchmarker.BenchmarkAsync(async () => await benchmark.Run(), attribute.Repetitions, false).Result;

我想从一开始就不再需要这个IBenchmark接口,在这一点上,它比任何事情都更妨碍我。我想做的不是传递benchmark.Run()我的 lambda,而是传递同一个类中另一个方法的反射调用。我试过这样的事情:

AsyncBenchmarker.BenchmarkAsync(async () => 
    await benchmark.GetType().GetMethod("SomeOtherMethod").Invoke(benchmark, null), attribute.Repetitions, false).Wait();

问题是Invoke返回一个可为空的对象,我需要它是可等待的。我怎样才能做到这一点?

标签: c#lambdareflectionasync-awaitfunc

解决方案


推荐阅读