我有一个使用.NET Core 3.1编写的应用程序,提供一个描述应用程序健康状况的端点,并有一个IHostedService在数据库中进行数据处理。
然而,问题在于,HostedService的工作函数开始长时间处理,结果导致Startup中的Configure()方法未被调用,/status端点没有运行。
我希望在HostedService启动之前,/status端点就能够开始运行。如何在Hosted Service之前启动端点?
示例代码:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddHostedService<SomeHostedProcessDoingHeavyWork>();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/status", async context =>
{
await context.Response.WriteAsync("OK");
});
});
}
}
托管服务(HostedService)
public class SomeHostedProcessDoingHeavyWork : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
await MethodThatRunsForSeveralMinutes();
await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken);
}
}
private async Task MethodThatRunsForSeveralMinutes()
{
// Process data from db....
return;
}
}
我尝试在Configure()
中添加HostedService
,但是app.ApplicationServices
是只读的ServiceProvider
。
ExecuteAsync
的主体移动到一个单独的方法中,然后在ExecuteAsync
中使用await DoWork(stoppingToken)
。您还可以尝试将await Task.Delay(1);
放置在第一行。服务的创建被阻塞,直到它们变成异步。我期望在第一个等待时立即变为异步,但文档中的类似示例使用我建议的第一种机制。 - pinkfloydx33Program.cs
中添加服务,而不是在Startup.ConfigureServices
中添加。否则服务器实际上并没有启动。 - user2146414