我有一个这样的用户控制器:
public class UserController : ControllerBase
{
private readonly IUserService _userService;
public UserController(IUserService userService)
{
_userService = userService;
}
public async Task<User> Get(int id, CancellationToken cancellationToken)
{
return await _userService.GetUserById(id, cancellationToken);
}
}
和用户服务:
public class UserService : IUserService
{
public async Task<User> GetUserById(int id, CancellationToken cancellationToken)
{
return await _dbContext.Users.Where(a => a.Id == id).FirstOrDefaultAsync(cancellationToken);
}
}
在UserService
我有一个async
方法,通过Id
.
我的问题是,我们需要使用async/await
关键字 incontroller
还是使用async/await
inUserService
就足够了?
public class UserController : ControllerBase
{
private readonly IUserService _userService;
public UserController(IUserService userService)
{
_userService = userService;
}
public Task<User> Get(int id, CancellationToken cancellationToken)
{
return _userService.GetUserById(id, cancellationToken);
}
}
如果您只等待一件事,作为方法的最后一行async
,并且直接返回结果或根本不返回结果(即不对结果做任何重要的事情),那么是的,您可以await
通过删除async
和await
部分; 这避免了一些机制,但这意味着如果您同步调用故障的方法(特别是:它抛出异常而不是返回报告故障状态的任务),那么异常将略微不同。
如果您处于内部循环中,例如在每次操作被多次调用的 IO 代码中间,并且您需要对其进行优化,那么避免此状态机可能很重要,但是:这在这里不适用 - 您是在控制器的顶部。老实说,它不需要优化:只需使用async
/ await
:它会更一致地正确。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句