Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I pass a non-awaitable action to a method that takes a Func<Task>?

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…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

_ = 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; } );
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading