What actually happens when using async/await inside a LINQ statement?

前端 未结 2 603
一个人的身影
一个人的身影 2020-12-05 07:20

The following snippet compiles, but I\'d expect it to await the task result instead of giving me a List>.

var foo = bars.Sel         


        
2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-05 07:55

    does it have a certain use

    Sure. With async and await inside a LINQ statement you can e.g. do something like this:

    var tasks = foos.Select( async foo =>
        {
            var intermediate =  await DoSomethingAsync( foo );
            return await DoSomethingElseAsync( intermediate );
        } ).ToList();
    await Task.WhenAll(tasks);
    

    Without async/await inside a LINQ statement you're not awaiting anything inside the LINQ statement, so you can't process the result, or await for something else.

    Without async/await, in the LINQ statement you're only starting tasks, but not waiting for them to complete. They'll still complete eventually, but it'll happen long after the control will leave the LINQ statement, so you can only access their results after the WhenAll line will complete, but not inside the LINQ statement.

提交回复
热议问题