The return type of an
async
function will need to be
Task<T>
or
ValueTask<T>
, so your delegate type will be either
Func<Task<T>>
or
Func<ValueTask<T>>
.
The function runner effectively doesn't care whether or not the function is async - it just calls the function and returns the result. You can make the method generic to allow any return type:
public static class FunctionRunner
{
public static T RunSuppliedFunction<T>(Func<T> theFunction) => theFunction();
}
If the delegate returns
Task<T>
or
ValueTask<T>
, the calling method will either need to return the result directly, or be marked as
async
and
await
the result:
private Task<int> theAsyncFunction = ...;
public Task<int> CallingMethod() => FunctionRunner.RunSuppliedFunction(theAsyncFunction);
public async Task<int> CallingMethod() => await FunctionRunner.RunSuppliedFunction(theAsyncFunction);
TBH, I don't think that the
FunctionRunner
class adds anything here - you could just call the
Func<>
directly.
public Task<int> CallingMethod() => theAsyncFunction();
public async Task<int> CallingMethod() => await theAsyncFunction();
Edit: Based on the updated question, you still need to update the definition of
RunSuppliedFunction
:
public static class FunctionRunner
{
public static Task<int> RunSuppliedFunction( Func<Task<int>> functionReturningInt ) => functionReturningInt();
}
private async Task<int> SomeFunction()
{
await Task.Delay( 100 );
return 42;
}
public async Task<int> CallingMethod()
{
return await FunctionRunner.RunSuppliedFunction( SomeFunction );
}