jeudi 28 octobre 2021

C# - Correct way to send a statement as a Func

I made a small benchmarking library that takes in Func<Task> objects, runs them a certain number of times and uses a Stopwatch object to figure out the average time it took to run:

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

I have made a small IBenchmark interface with a single Run() method. The way I am currently using this library is making benchmark classes that implement IBenchmark and passing a lambda that calls the Run method to it. Those IBenchmark objects are added to DI via an extension method:

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

I would like to move away from needing this IBenchmark interface in the first place, it is getting in my way more than anything at this point. What I would like to do instead of passing benchmark.Run() in my lambda is pass a reflective invocation of another method in that same class. I tried something like this:

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

The problem is that Invoke returns a nullable object and I need this to be awaitable. How can I achieve this?





Aucun commentaire:

Enregistrer un commentaire