繁体   English   中英

当控制器已经在 ASP .NET 核心中使用异步时,服务中的方法是否也必须是异步的?

[英]Do the methods in the services also have to be async when the controller is already using async in ASP .NET core?

我对 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 上的异步代码实际上使每个请求的运行速度稍慢,但它也减少了应用程序使用的线程数,从而允许它处理更多的并发请求。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM