IHostedService无原因停止

11

有人可以解释一下为什么我的服务器无缘无故停止了吗? 以下是我的IHostedService实现:

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();
        }
    }

这是我的日志吗?

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

为什么在使用Kestrel (.Net Core)的IIS时我的方法会挂起?

通常情况下,由于调用API,我的< strong>while(true)代码块会重新启动。但是作为后台任务的< strong>IHostedService不应该停止,对吗?

相关帖子请参考github


2
我可能错了,但据我所记,IIS能够在网站没有活动时停止网站池,并在活动开始时唤醒它。您可以检查池设置,其中有一些相关内容。 - tym32167
你能否在启动和关闭时记录一些内容,以缩小问题的范围?事件查看器(Event Viewer)中是否有任何有趣的信息? - mjwills
1个回答

25

用户tym32167正在正确的路上。在部署节中,IHostedService文档中提到:

在IIS或常规的Azure App Service中,由于应用程序池的回收,您的主机可能会被关闭。

IIS应用程序池有默认的空闲超时时间为20分钟,并且它们还有一个默认的应用程序池回收时间为29小时。通常情况下,您需要将空闲超时时间设置为零(禁用),并将回收时间设置为最小化对系统造成危害的固定时间。

这里有一篇有趣的博客文章解释了为什么他们选择了29小时,也包括了空闲超时时间,链接在此

另外,如果您正好要部署到Azure上,之前链接的文章建议可以使用其他方式进行部署,例如容器、WebJobs等,以确保服务能够全天候运行。


有没有其他解决方案,而不需要更改IIS(应用程序池)的设置。我的意思是我想保持IIS的默认设置。因为如果IIS从未回收,它可能会占用更多的内存。这就是为什么我在寻找其他解决方案。 - Pratik 1020

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接