2

I have the following methods:

private async Task<T> GetStuff<T>() {}
private async Task<T> DoStuff<T>(int id, Func<Task<T>> func) {}

My question here is this: What is the appropriate way use the lambda expression for GetStuff() when invoking the DoStuff()method, with regards to async and await?

public async Task<T> InvokeStuff<T>()
{
    // option 1: keeping it simple
    return await DoStuff(1, () => GetStuff<T>());

    // option 2: verbose
    return await DoStuff(1, async () => await GetStuff<T>());

    // option 3: ???
}

The difference here is wether or not one sets the async keyword at the lambda input parameters and an await at the expression body's invocation of other async methods.

As far as I can tell, both option 1 and option 2seem to work fine, which makes me think option 2 is simply redundant or possibly harmful.

-S

Edit: It has been suggested that this is a duplicate of What is the purpose of "return await" in C#?

However, that is a gross simplification. The other issue deals with the simple use of an await within an async method context. This is a question on wether or not to introduce the async context when declaring a lambda expression.

Sigurd Garshol
  • 1,376
  • 3
  • 15
  • 36
  • [Blog post on the subject](http://blog.stephencleary.com/2016/12/eliding-async-await.html). The two are almost equivalent. Using the keywords does introduce a state machine and will capture context. In this case, eliding the keywords is appropriate. – Stephen Cleary Aug 22 '19 at 12:49
  • I am not sure that a post on a random blog equates to a duplicate stackoverflow post. Perhaps you should "elide" marking this as a duplicate unless there is infact a duplicate post? – Sigurd Garshol Aug 22 '19 at 14:06

1 Answers1

1

Here's a blog post on the subject that dives into more detail. There's also this Stack Overflow post that is very similar except it deals with methods and your question deals with lambdas (which are converted by the compiler into methods).

In summary, the two approaches are almost equivalent. Using the keywords does introduce a state machine and will cause the await to capture context. In this case - since the lambda just calls a single method and returns its result - eliding the keywords is appropriate.

Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810