c# - 当控制器已经在 ASP .NET 核心中使用异步时,服务中的方法是否也必须是异步的?
问题描述
我对 ASP .NET CORE 中的异步编程非常陌生。我为我的校验令牌功能制作了服务和控制器。这是我在Authservice中的方法:
public AppUser CheckToken(string token)
{
if (token == null || string.IsNullOrWhiteSpace(token))
throw new CustomUnauthorizedException("Unauthorized", "You are not authorized to perform this action");
var user = _context.DbSet<AppUser>().Query.FirstOrDefault(x => x.TOKEN == token);
if (user == null)
throw new CustomUnauthorizedException("Unauthorized", "You are not authorized to perform this action");
return user;
}
这是我在控制器中的方法:
[HttpGet("{Id}")]
public async Task<ActionResult<IEnumerable<Follow>>> GetFollows([FromHeader]string token, long Id)
{
var user = _authService.CheckToken(token);
return await _context.DbSet<Follow>().Query.Where(x => x.Id == Id && x.UserId ==
user.UserId).ToListAsync();
}
我的代码运行良好,但一位同事建议我这样做:
您对数据库所做的一切都必须使用 async 和 Task
他建议我也异步编写服务方法
我使用依赖注入以异步方法从服务中调用该方法。
我的问题:
我是否还需要在异步任务中编写服务中的方法?
这是使用异步编程的正确方法吗?
我使用过的来源:
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/
解决方案
作为一般规则,任何 I/O 代码都应在 ASP.NET Core 应用程序中异步完成。这包括所有数据库查询。
ASP.NET 上的异步代码实际上使每个请求的运行速度稍慢,但它也减少了应用程序使用的线程数,从而允许它处理更多的同时请求。
推荐阅读
- python - 如何将 python 程序设置为 Windows 中的默认 Web 浏览器?
- c++ - c++ - 在类内或类外访问时相同变量的 cout 但不同的输出
- swift - 如何使用 oauth2 和 swift 对自定义 Web 服务进行身份验证
- jquery - 用类将每个元素包装成 div 并包装子元素
- java - 防止控制器响应
- apache-spark - spark.python.worker.reuse 没有按预期工作
- asp.net - 有没有办法在 ASP.NET 项目中预编译 React jsx 文件?
- javascript - 如果行没有换行符,是否可以知道我的光标是在文本区域的第一行还是最后一行?
- android - 具有透明度的直接加载图像的 Webview 背景
- html - Bootstrap 和 Angular 未捕获的 TypeError