Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/reporting-services/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net core asp.net核心托管服务在api不活动后休眠_Asp.net Core_Asp.net Core Webapi_Asp.net Core 2.1_Asp.net Core Hosted Services - Fatal编程技术网

Asp.net core asp.net核心托管服务在api不活动后休眠

Asp.net core asp.net核心托管服务在api不活动后休眠,asp.net-core,asp.net-core-webapi,asp.net-core-2.1,asp.net-core-hosted-services,Asp.net Core,Asp.net Core Webapi,Asp.net Core 2.1,Asp.net Core Hosted Services,我有一个托管服务,每分钟检查一个电子邮件帐户。我还将MVC与Web API 2.1结合使用。为了启动托管服务,我必须通过调用API方法“唤醒它”。在Web API处于非活动状态一段时间后,托管服务进入休眠状态并停止检查电子邮件。这就像是在收集垃圾。如何使其连续运行 我们将不胜感激 Startup.cs: public void ConfigureServices(IServiceCollection services) { services.AddSwaggerGen(c

我有一个托管服务,每分钟检查一个电子邮件帐户。我还将MVC与Web API 2.1结合使用。为了启动托管服务,我必须通过调用API方法“唤醒它”。在Web API处于非活动状态一段时间后,托管服务进入休眠状态并停止检查电子邮件。这就像是在收集垃圾。如何使其连续运行

我们将不胜感激

Startup.cs:

public void ConfigureServices(IServiceCollection services)
    {
        services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {Title = "CAS API", Version = "v1"});

                // Set the comments path for the Swagger JSON and UI.
                var xmlFile = $"{Assembly.GetEntryAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);
            })

            .AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                    builder => builder.WithOrigins(Configuration["uiOrigin"])
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .AllowCredentials());
            })
            .AddHostedService<EmailReceiverHostedService>()
            .Configure<EmailSettings>(Configuration.GetSection("IncomingMailSettings"))
            .AddSingleton<IEmailProcessor, MailKitProcessor>()
            .AddSingleton<IEmailRepository, EmailRepository>()


          ...
using CasEmailProcessor.Options;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using System.Threading;
using System.Threading.Tasks;

public class EmailReceiverHostedService : IHostedService, IDisposable
{
    private readonly ILogger _logger;
    private readonly Timer _timer;
    private readonly IEmailProcessor _processor;
    private readonly EmailSettings _emailConfig;


    public EmailReceiverHostedService(ILoggerFactory loggerFactory,
        IOptions<EmailSettings> settings,
        IEmailProcessor emailProcessor)
    {
        _logger = loggerFactory.CreateLogger("EmailReceiverHostedService");
        _processor = emailProcessor;
        _emailConfig = settings.Value;
        _timer = new Timer(DoWork, null, Timeout.Infinite, Timeout.Infinite);
    }

    public Task StartAsync(CancellationToken cancellationToken)
    {
        _logger.LogInformation("Timed Background Service is starting.");
        StartTimer();
        return Task.CompletedTask;
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        _logger.LogInformation("Timed Background Service is stopping.");
        StopTimer();

        return Task.CompletedTask;
    }

    public void Dispose()
    {
        _timer?.Dispose();
    }

    private void StopTimer()
    {
        _timer?.Change(Timeout.Infinite, 0);
    }
    private void StartTimer() { _timer.Change(TimeSpan.FromSeconds(_emailConfig.TimerIntervalInSeconds), TimeSpan.FromSeconds(_emailConfig.TimerIntervalInSeconds)); }

    private void DoWork(object state)
    {
        StopTimer();
        _processor.Process();
        StartTimer();
    }
}
public void配置服务(IServiceCollection服务)
{
services.AddSwaggerGen(c=>
{
c、 大摇大摆的文档(“v1”,新信息{Title=“CAS API”,Version=“v1”});
//为Swagger JSON和UI设置注释路径。
var xmlFile=$“{Assembly.GetEntryAssembly().GetName().Name}.xml”;
var xmlPath=Path.Combine(AppContext.BaseDirectory,xmlFile);
c、 includexmlcoments(xmlPath);
})
.AddCors(选项=>
{
options.AddPolicy(“CorsPolicy”,
builder=>builder.WithOrigins(配置[“uiOrigin”])
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
})
.AddHostedService()
.Configure(Configuration.GetSection(“IncomingMailSettings”))
.AddSingleton()
.AddSingleton()
...
EmailReceiverHostedService.cs:

public void ConfigureServices(IServiceCollection services)
    {
        services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {Title = "CAS API", Version = "v1"});

                // Set the comments path for the Swagger JSON and UI.
                var xmlFile = $"{Assembly.GetEntryAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);
            })

            .AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                    builder => builder.WithOrigins(Configuration["uiOrigin"])
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .AllowCredentials());
            })
            .AddHostedService<EmailReceiverHostedService>()
            .Configure<EmailSettings>(Configuration.GetSection("IncomingMailSettings"))
            .AddSingleton<IEmailProcessor, MailKitProcessor>()
            .AddSingleton<IEmailRepository, EmailRepository>()


          ...
using CasEmailProcessor.Options;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using System.Threading;
using System.Threading.Tasks;

public class EmailReceiverHostedService : IHostedService, IDisposable
{
    private readonly ILogger _logger;
    private readonly Timer _timer;
    private readonly IEmailProcessor _processor;
    private readonly EmailSettings _emailConfig;


    public EmailReceiverHostedService(ILoggerFactory loggerFactory,
        IOptions<EmailSettings> settings,
        IEmailProcessor emailProcessor)
    {
        _logger = loggerFactory.CreateLogger("EmailReceiverHostedService");
        _processor = emailProcessor;
        _emailConfig = settings.Value;
        _timer = new Timer(DoWork, null, Timeout.Infinite, Timeout.Infinite);
    }

    public Task StartAsync(CancellationToken cancellationToken)
    {
        _logger.LogInformation("Timed Background Service is starting.");
        StartTimer();
        return Task.CompletedTask;
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        _logger.LogInformation("Timed Background Service is stopping.");
        StopTimer();

        return Task.CompletedTask;
    }

    public void Dispose()
    {
        _timer?.Dispose();
    }

    private void StopTimer()
    {
        _timer?.Change(Timeout.Infinite, 0);
    }
    private void StartTimer() { _timer.Change(TimeSpan.FromSeconds(_emailConfig.TimerIntervalInSeconds), TimeSpan.FromSeconds(_emailConfig.TimerIntervalInSeconds)); }

    private void DoWork(object state)
    {
        StopTimer();
        _processor.Process();
        StartTimer();
    }
}
使用CasEmailProcessor.Options;
使用Microsoft.Extensions.Hosting;
使用Microsoft.Extensions.Logging;
使用Microsoft.Extensions.Options;
使用制度;
使用系统线程;
使用System.Threading.Tasks;
公共类EmailReceiverHostedService:IHostedService,IDisposable
{
专用只读ILogger\u记录器;
专用只读定时器_定时器;
专用只读IEmailProcessor\u处理器;
专用只读电子邮件设置\u emailConfig;
公共电子邮件接收方托管服务(iLogger工厂、Logger工厂、,
IOPS设置,
电子邮件处理器(emailProcessor)
{
_logger=loggerFactory.CreateLogger(“EmailReceiverHostedService”);
_处理器=电子邮件处理器;
_emailConfig=settings.Value;
_定时器=新定时器(DoWork,null,Timeout.Infinite,Timeout.Infinite);
}
公共任务StartSync(CancellationToken CancellationToken)
{
_logger.LogInformation(“定时后台服务正在启动”);
StartTimer();
返回Task.CompletedTask;
}
公共任务StopAsync(CancellationToken CancellationToken)
{
_logger.LogInformation(“定时后台服务正在停止”);
停止计时器();
返回Task.CompletedTask;
}
公共空间处置()
{
_计时器?.Dispose();
}
私有void StopTimer()
{
_计时器?更改(Timeout.Infinite,0);
}
私有void StartTimer(){u timer.Change(TimeSpan.FromSeconds(_emailConfig.TimerIntervalInSeconds),TimeSpan.FromSeconds(_emailConfig.TimerIntervalInSeconds));}
私有无效工作(对象状态)
{
停止计时器();
_Process();
StartTimer();
}
}

正如您所想,根本原因是,在IIS中托管时,由于应用程序池回收,您的主机可能会关闭。下面已经指出了这一点:

请务必注意,您部署ASP.NET核心Web主机或.NET核心主机的方式可能会影响最终解决方案。例如,如果您将Web主机部署在IIS或常规Azure应用程序服务上,则您的主机可能会因应用程序池回收而关闭

对于可能的解决方法,您可以尝试将空闲超时设置为零以禁用默认回收

由于IIS去氟酸循环,您可以考虑不同的宿主细胞:

  • 使用Windows服务

  • 使用Docker容器(Windows容器),但为此,您需要Windows Server 2016或更高版本

  • 使用Azure函数


对于您的场景,您可以尝试在Windows事件计划程序上创建任务来访问URL以唤醒服务


powershell.exe-命令{Invoke WebRequest}

您使用什么来托管API?可能配置了一个空闲超时,表示
如果我在x分钟内没有收到任何请求,请关闭以节省内存
我正在使用IIS托管应用程序池中存在20分钟的“空闲”超时。我将查看日志,看看它是否在20分钟后超时,然后将超时时间增加到40分钟。最终,我可能需要在win服务中托管电子邮件部分。您可以将应用程序配置为始终运行,请阅读本文: