When is the best place to use Task.Result instead of awaiting Task

前端 未结 4 692
小鲜肉
小鲜肉 2020-12-31 19:09

Whilst I\'ve been using async code in .NET for a while, I\'ve only recently started to research it and understand what\'s going on. I\'ve just been going through my code an

4条回答
  •  甜味超标
    2020-12-31 20:11

    Have you considered this version?

    var userTask = _userRepo.GetByUsername(User.Identity.Name);
    
    //Some work that doesn't rely on the user object
    
    user = await _userRepo.UpdateLastAccessed(await userTask, DateTime.Now);
    
    return user;
    

    This will execute the "work" while the user is retrieved, but it also has all the advantages of await that are described in Await on a completed task same as task.Result?


    As suggested you can also use a more explicit version to be able to inspect the result of the call in the debugger.

    var userTask = _userRepo.GetByUsername(User.Identity.Name);
    
    //Some work that doesn't rely on the user object
    
    user = await userTask;
    user = await _userRepo.UpdateLastAccessed(user, DateTime.Now);
    
    return user;
    

提交回复
热议问题