Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
978 views
in Technique[技术] by (71.8m points)

c# - Graceful shutdown in IHostedService in asp.net core api

I got a problem with my asp net core api project. I try to implement some basic checks (for example db-connectivity) and if the check fails, I want to graceful shutdown my application.
For that, I implement the interface IHostedService and add it as a hostedService within the ConfigureServices method of my startup class (services.AddHostedService<MyService>();).

The StartAsync implementation of MyService looks currently like that:

public Task StartAsync(CancellationToken cancellationToken){
    applicationLifetime.StopApplication();
}

And the variable applicationLifetime is of type IHostApplicationLifetime and is injected from the DI-Service. I get the following exception:

[15:58:42 FTL] Unable to start Kestrel.
System.Threading.Tasks.TaskCanceledException: A task was canceled.
   at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerImpl.BindAsync(CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerImpl.StartAsync[TContext](IHttpApplication`1 application, CancellationToken cancellationToken)
Unhandled exception. System.Threading.Tasks.TaskCanceledException: A task was canceled.
   at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerImpl.BindAsync(CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerImpl.StartAsync[TContext](IHttpApplication`1 application, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Hosting.GenericWebHostService.StartAsync(CancellationToken cancellationToken)
   at Microsoft.Extensions.Hosting.Internal.Host.StartAsync(CancellationToken cancellationToken)
   at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(IHost host, CancellationToken token)
   at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(IHost host, CancellationToken token)
   at Program.Main(String[] args) in Program.cs:line 31
   atProgram.<Main>(String[] args)

and line 31 of my Programm.cs class is part of the main method with await host.RunAsync();

My goal is to stop the application before other hostedServices run or the api can handle requests.

question from:https://stackoverflow.com/questions/65939753/graceful-shutdown-in-ihostedservice-in-asp-net-core-api

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...