Suppose I have a method as follows…
public static async Task DoIt(Func<Task> doit) {
// Do something first
await doit();
// Do something last
}
I can pass in an awaitable function as follows…
await DoIt(() => Task.Delay(1000));
If I want to pass in something non-awaitable, I can do it like this…
_ = DoIt(() => Task.Run(() => Console.WriteLine("Hi")));
…but this seems quite ugly. Is there a neater way of doing this?
>Solution :
If the action is an async, non-awaitable method (e.g. async void) there isn’t really a proper way to return a task. There is no way to return a task that signals its completion when the async void method finishes.
If the action is a synchronous method, you can just return Task.CompletedTask.
_ = DoIt(() => { Console.WriteLine("Hi"); return Task.CompletedTask; } );