1

In the code below, is there a difference between the calls in WithoutInnerAwaitand WithInnerAwait?

Or in other words:

When using a lambda to wrap an async function, do I need to mark the lambda as async and use await inside? Or is it enough to simply await the lambda when it's called?

private async Task DoStuff(Func<Task> lambda)
{
    await lambda();
}

public async Task WithoutInnerAwait()
{
    await DoStuff(() => Task.Delay(5000));
}

public async Task WithInnerAwait()
{
    await DoStuff(async () => await Task.Delay(5000));
}
LcdDrm
  • 1,009
  • 7
  • 14
  • The only observable difference is when exceptions are thrown and what the stack trace would contain. – Jeremy Lakeman Aug 16 '22 at 06:41
  • I've marked your question as a duplicate of two others. Taking `WithoutInnerAwait`, your code is essentially the same as `await DoStuff(SomeMethod);` where `SomeMethod` is declared as `public Task SomeMethod() { return Task.Delay(5000); }`. Your `WithInnerAwait` is the same except the `SomeMethod` would be async and contain `await`. As such, your question is really about the difference between returning `Task` and awaiting. – ProgrammingLlama Aug 16 '22 at 06:43
  • 1
    Check out the article [Eliding Async and Await](https://blog.stephencleary.com/2016/12/eliding-async-await.html) by Stephen Cleary. It's quite informative about this topic. – Theodor Zoulias Aug 16 '22 at 07:19

0 Answers0