如何在Lambda中使用async/await [英] how to use async/await inside a lambda
问题描述
如何在lambda表达式中正确使用async/await关键字?这是代码:
How can I use the async/await keywords correctly in a lambda expression ? here is the code :
public async Task<IHttpActionResult> GetUsers() {
var query = await _db.Users.ToListAsync();
var users = query.Select(async u => new
{
FirstName = u.FirstName,
LastName = u.LastName,
IsGeek = await _userManager.IsInRoleAsync(u.Id, "Geek")
});
return Ok(users);
}
如您所见,此代码在webapi控制器中运行,它可以编译而没有任何错误,问题在于它需要在某个地方添加 extra (await
),因为此操作永远不会恢复.
As you can see this code is running inside a webapi controller, it compiles without any error, the problem is it needs an extra await
somewhere because this action never retuns.
请注意,_db
和_usermanager
是应用程序的DbContext
和UserManager
.
Notice that _db
and _usermanager
are the DbContext
and the UserManager
for the application.
谢谢.
更新:
此等效代码永远不会失败(但它不是优美的:():
This equivalent code never fails (but it's not ellegant :( ):
var query = await _db.Users.ToListAsync();
var users = new List<object>();
foreach (var u in query)
{
bool IsGeek = await _userManager.IsInRoleAsync(u.Id, "IsGeek");
users.Add( new {
FirstName = u.FirstName,
LastName = u.LastName,
IsGeek= IsGeek
});
}
return Ok(users);
推荐答案
考虑您的类型.
var query = await _db.Users.ToListAsync();
query
是用户列表.
var users = query.Select(async u => new
{
FirstName = u.FirstName,
LastName = u.LastName,
IsGeek = await _userManager.IsInRoleAsync(u.Id, "Geek")
});
当您使用async
lambda Select
时,结果是任务序列.因此,要(异步)等待所有这些任务完成,请使用Task.WhenAll
:
When you Select
with an async
lambda, the result is a sequence of tasks. So, to (asynchronously) wait for all those tasks to complete, use Task.WhenAll
:
var result = await Task.WhenAll(users);
return Ok(result);
这篇关于如何在Lambda中使用async/await的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!