从任务列表中获取结果

时间:2017-11-02 19:03:14

标签: asynchronous lambda asp.net-core async-await task

我知道之前已经问过,但我根本无法弄清楚如何做到这一点。

因此,下面的代码显然是错误的,因为我await在查询中{。}}。

    // GET: /<controller>/
    [HttpGet]
    public new IActionResult Index()
    {
        var model = new List<Models.ViewModels.ApplicationUser.ListViewModel>();
        model = _userManager.Users.Select(u => new Models.ViewModels.ApplicationUser.ListViewModel
        {
            Id = u.Id,
            Email = u.Email,
            Name = u.GivenName + " " + u.SurName,
            RoleNames = await _userManager.GetRolesAsync(u)
        }).ToList();
        return View(model);
    }

这使得以下错误显示:“”await“运算符只能在异步lambda表达式中使用”。

所以,我先完成查询,然后让lambda异步:

    // GET: /<controller>/
    [HttpGet]
    public new IActionResult Index()
    {
        var model = new List<Models.ViewModels.ApplicationUser.ListViewModel>();
        // get users first, so I don't have to async something in a Select
        var users = _userManager.Users.ToList();
        // make the lambda asyc
        model = users.Select(async u => new Models.ViewModels.ApplicationUser.ListViewModel
        {
            Id = u.Id,
            Email = u.Email,
            Name = u.GivenName + " " + u.SurName,
            RoleNames = await _userManager.GetRolesAsync(u)
        }).ToList();
        return View(model);
    }

然后我得到Cannot implicitly convert type 'System.Collections.Generic.List<System.Threading.Tasks.Task<Models.ViewModels.ApplicationUser.ListViewModel>>' to 'System.Collections.Generic.List<Models.ViewModels.ApplicationUser.ListViewModel>'

所以基本上(我猜)它说我有一个Task的列表,我应该得到结果。但是如何从Task获得结果呢?或者更好:最好的方法是什么?

我已经检查了thisthis以及this,但没有靠近。

1 个答案:

答案 0 :(得分:1)

名为model的变量属于List<Task<ApplicationUser>>类型。要获得List<ApplicationUser>,您只需要await所有任务。此外,现在,获取所有用户的呼叫是阻止变体,您可以将其切换为ToListAsync。试试这个:

[HttpGet]
public async Task<IActionResult> Index() {
    var model = new List<Models.ViewModels.ApplicationUser.ListViewModel>();
    // get users first, so I don't have to async something in a Select
    var users = await _userManager.Users.ToListAsync();
    // make the lambda asyc
    modelTasks = users.Select(async u => new Models.ViewModels.ApplicationUser.ListViewModel {
        Id = u.Id,
        Email = u.Email,
        Name = u.GivenName + " " + u.SurName,
        RoleNames = await _userManager.GetRolesAsync(u)
    }).ToList();
    var users = await Task.WhenAll(modelTasks);
    return View(users);
}