How to write a method that can handle Task and ValueTask?
06:18 10 May 2017

Imagine you want to write a method similar to the following one. It wraps a function returning a ValueTask with trivial performance monitoring code:

static async Task Measure(Func> body)
{
    Console.WriteLine($"Starting perf test");
    var sw = Stopwatch.StartNew();
    await body();
    sw.Stop();
    Console.WriteLine(sw.Elapsed);
}

My question is: Is there a way to write this function once so that it can receive Func> and Func>?

Of course you could simply duplicate the code and change just the parameter's type.

static async Task Measure(Func> body) { ... }

The implementation would be absolutely identical. I am asking myself if it is possible to avoid this kind of code duplication when having to deal with ValueTask and Task. Up to now, I could not come up with a good solution. Any ideas?

c# task task-parallel-library valuetask