Far*_*ani 4 c# asynchronous threadpool async-await
我有一个这样的用户控制器:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
和用户服务:
public class UserService : IUserService
{
public async Task<User> GetUserById(int id, CancellationToken cancellationToken)
{
return await _dbContext.Users.Where(a => a.Id == id).FirstOrDefaultAsync(cancellationToken);
}
}
Run Code Online (Sandbox Code Playgroud)
在UserService我有一个async方法,通过Id.
我的问题是,我们需要使用async/await关键字 incontroller还是使用async/awaitinUserService就足够了?
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);
}
}
Run Code Online (Sandbox Code Playgroud)
如果您只等待一件事,作为方法的最后一行async,并且直接返回结果或根本不返回结果(即不对结果做任何重要的事情),那么是的,您可以await通过删除async和await部分; 这避免了一些机制,但这意味着如果您同步调用故障的方法(特别是:它抛出异常而不是返回报告故障状态的任务),那么异常将略微不同。
如果您处于内部循环中,例如在每次操作被多次调用的 IO 代码中间,并且您需要对其进行优化,则避免此状态机可能很重要,但是:这在这里不适用 - 您是在控制器的顶部。老实说,它不需要优化:只需使用async/ await:它会更一致地正确。
| 归档时间: |
|
| 查看次数: |
137 次 |
| 最近记录: |