Why does Task.WhenAll return void?

蓝咒 提交于 2019-12-10 10:58:06

问题


This is the code from the image above:

if (claims != null && claims.Any())
{
    // firstly, why doesn't this work?
    // var _claimResults = from claim in claims select UserManager.AddClaimAsync(user.Id, claim);

    // but this does...
    List<Task> _claimResults = new List<Task>();
    foreach (var claim in claims)
    {
        _claimResults.Add(UserManager.AddClaimAsync(user.Id, claim));   
    }

    // secondly, why does Task.WhenAll return void when it clearly says it returns Task?
    Task claimsResult = await Task.WhenAll(_claimResults);
}
  1. Why doesn't the LINQ expression work, yet the foreach does. The LINQ expression gives me a "underlying provider failed to open" exception on execution.
  2. Why does Task.WhenAll() return void when it says it's return type is Task?

Edit: claims is a List<Claim> which I think is List<System.Security.Claim>.


回答1:


WhenAll returns a Task, but then you're awaiting that task. Awaiting a plain Task (rather than a Task<T>) gives no result. So you either want:

Task claimsResult = Task.WhenAll(_claimResults);

or

await Task.WhenAll(_claimResults);

My suspicion is that the LINQ problem is because your foreach approach materializes the query immediately - the LINQ equivalent would be:

var _claimsResults = claims.Select(claim => UserManager.AddClaimAsync(user.Id, claim))
                           .ToList();

... where the ToList() method materializes the results immediately. (I've used the method call syntax rather than query expression syntax because query expressions are pretty pointless for trivial queries like this.)




回答2:


Not sure about #1, but for #2 its because you called await on it

it should be

Task claimsResult = Task.WhenAll(_claimResults);
await claimsResult;

or omit the variable entirely if you don't need to delay the await somewhere else



来源:https://stackoverflow.com/questions/38978057/why-does-task-whenall-return-void

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!