Could anyone explain to me why my server stopped for no reason? below my IHostedService implementation:
public class HostServiceBox : IHostedService
{
public Task StartAsync(CancellationToken cancellationToken)
{
return Task.Run(() =>
{
DomonutyBoxBusiness.StartBoxListening(); //STARTUP Box listening
while (true)
{
Logging.Info(DateTime.Now + " HostServiceBox Running");
Thread.Sleep(10000);
}
}, cancellationToken);
}
public Task StopAsync(CancellationToken cancellationToken)
{
Logging.Info(DateTime.Now + " StopAsync");
//TODO impplement a Stop litening all boxes
throw new NotImplementedException();
}
}
Here is my log?
.....
2/24/2018 8:31:27 PM HostServiceBox Running
2/24/2018 8:32:27 PM HostServiceBox Running
2/24/2018 8:33:27 PM HostServiceBox Running
2/24/2018 8:34:27 PM HostServiceBox Running <------
2/25/2018 11:22:07 AM HostServiceBox Running <-----
2/25/2018 11:23:07 AM HostServiceBox Running
2/25/2018 11:24:07 AM HostServiceBox Running
2/25/2018 11:25:07 AM HostServiceBox Running
......
is look like on IIS with kestrel (.Net Core) my method slept ? Why?
Usualy my while(true) restart because i call the API. But IHostedService is a background task it's shouldnt stop right?
related post on github
In ASP.NET Core, background tasks can be implemented as hosted services. A hosted service is a class with background task logic that implements the IHostedService interface. This article provides three hosted service examples: Background task that runs on a timer. Hosted service that activates a scoped service.
StopAsync is called when the application receives the shut down ( SIGTERM ) signal, for example when you push CTRL+C in the console window, or the app is stopped by the host system. This allows you to close any open connections, dispose resources, and generally clean up your class as required.
User tym32167 is on the right track. This is mentioned in the documentation for IHostedService
in the section on deployment:
on IIS or a regular Azure App Service, your host can be shut down because of app pool recycles
IIS app pools have a default idle-timeout of 20 minutes, and they also have a default app pool recycle time of 29 hours. Typically you want to set the idle timeout to zero (disabled) and the recycle to a fixed time where it will do the least harm.
There's an interesting blog post about why they chose 29 hours here and it also covers idle timeout.
Also, if you happen to be deploying to Azure, that article linked earlier suggests other ways to deploy that will truly run full-time (containers, WebJobs, etc).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With