11

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

btbenjamin
  • 593
  • 7
  • 19
  • 2
    I could be wrong, but as far as I remember IIS able to stop website pool when there no activity on website and awake it when activity starts. You can check pool settings, there was something related this – tym32167 Feb 27 '18 at 10:45
  • Are you able to log something at startup and shutdown, to narrow down the cause? Is there anything interesting in `Event Viewer`? – mjwills Feb 27 '18 at 11:25

1 Answers1

25

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).

McGuireV10
  • 9,572
  • 5
  • 48
  • 64
  • Is any other solution without change setting IIS (App Pool). I mean i want to keep default setting in IIS. because if IIS is never recycle then it may catch more memory. that's why I looking for other else this is ok – Pratik 1020 Apr 26 '22 at 14:36