I have a list of tasks that I created like this:
public async Task<IList<Foo>> GetFoosAndDoSomethingAsync()
{
var foos = await GetFoosAsync();
var tasks = foos.Select(async foo => await DoSomethingAsync(foo)).ToList();
...
}
By using .ToList()
, the tasks should all start. Now I want to await their completion and return the results.
This works in the above ...
block:
var list = new List<Foo>();
foreach (var task in tasks)
list.Add(await task);
return list;
It does what I want, but this seems rather clumsy. I'd much rather write something simpler like this:
return tasks.Select(async task => await task).ToList();
... but this doesn't compile. What am I missing? Or is it just not possible to express things this way?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…