在 ASP.NET 核心中添加 IHostedService 服务时无法访问 API

Cannot access APIs when add IHostedService service in ASP.NET Core

我使用 .NET 6,当我在 ASP.NET Core 中添加 IHostedService 服务时,我无法访问 API。如果删除 IHostedService,我就可以访问 API。

添加 IHostedService:

//builder.Services.AddHostedService<WSService>();
builder.WebHost.ConfigureServices(services => services.AddHostedService<WSService>());
public class WSService : IHostedService
{
    public async Task StartAsync(CancellationToken cancellationToken)
    {
        while (true)
        {
            System.Console.WriteLine("back ground task");
            await Task.Delay(5 * 1000);
        }
    }
    public async Task StopAsync(CancellationToken cancellationToken)
    {
        await Task.CompletedTask;
    }
}

如果添加IHostedService,无法访问http://localhost:5000/Query

namespace Api.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class QueryController : ControllerBase
    {
        private readonly IQueryData _queryData;

        public QueryController(IQueryData queryData)
        {
            _queryData = queryData;
        }

        [HttpGet]
        public async Task<IActionResult> Query([FromQuery] QueryDataRequest request, CancellationToken cancellationToken)
        {
            var data = await _queryData.PagingQueryAsync(request, cancellationToken);
            return new JsonResult(data);
        }

    }
}

添加IHostedService不会打印这些日志,看来WebHost不是运行

请问如何解决这个问题,谢谢!

您在 StartAsync 方法上造成了无限循环,正如文档 here:

所指出的

StartAsync should be limited to short running tasks because hosted services are run sequentially, and no further services are started until StartAsync runs to completion.