首页 > 解决方案 > 当控制器已经在 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/

标签: c#asp.netmultithreadingasp.net-coreasynchronous

解决方案


作为一般规则,任何 I/O 代码都应在 ASP.NET Core 应用程序中异步完成。这包括所有数据库查询。

ASP.NET 上的异步代码实际上使每个请求的运行速度稍慢,但它也减少了应用程序使用的线程数,从而允许它处理更多的同时请求。


推荐阅读