2

this is a stupid question but somehow it makes me feel I am missing something. Is there any difference in execution for async lambda and normal method? Like this

var tasks = list.Select(async c => { /* await somewhere */});
await Task.WhenAll(tasks);

and that

async Task<object> GetSomething(object c) { /* await somewhere */}
// ...
var task = list.Select(GetSomething);
await Task.WhenAll(tasks);

edit: I am asking because I have misconceptions if it is possible for the lambda to behave differently then a normal method. Provided that both the lambda and the method have the same body, is it possible that the lambda would create a void task? or the execution would not work as expected?

thank you, I haven't expected that fast response!

Marek Salát
  • 111
  • 1
  • 5
  • 3
    "All" that `async` does is change what code you can write inside the body it associates with (specifically, it changes it from "C# without the `await` keyword" to "C# with the `await` keyword") and changes how the return value (if any) is handled. It's an *implementation* detail of the method/lambda. It has *no* external effects visible to a caller (I always think it unfortunate that it appears in a position that makes it look like part of a method signature when in fact it plays no part there) – Damien_The_Unbeliever Oct 11 '17 at 07:39
  • 2
    there actually is a small difference between lambda and method groups, because lambdas resolve based on return value as well. But it's probably not something you need to worry about in your example. But for reference, you can read about it [here](https://stackoverflow.com/questions/5203792/overloaded-method-group-argument-confuses-overload-resolution) or [here](https://stackoverflow.com/questions/46505262/the-call-is-ambiguous-between-funct-and-functaskt) – default Oct 11 '17 at 08:08
  • I am asking because I have misconceptions if it is possible for the lambda to behave differently then a normal method. Provided that both the lambda and the method have the same body, is it possible that the lambda would create a void task? or the execution would not work as expected? that are the use cases where it would not work the same way? – Marek Salát Oct 11 '17 at 08:45

1 Answers1

5

A lambda creates either an anonymous method or an expression tree, depending on whether it's used in a context accepting a delegate or an Expression<...> type. In those cases where it creates an anonymous method, it's just like what it would've been had you written the method explicitly. Captured variables may change where the method gets defined, but it'll always be a real method that's seen as such by the runtime. The async keyword does not change that.