在AspNetCore应用程序上运行进程而不会超时

时间:2018-05-24 15:56:12

标签: c# asp.net-core

我是import re ... beschreibung_container = container.find_all("pre", {"class":"is24qa-objektbeschreibung text-content short-text"}) or "" beschreibung = beschreibung_container[0].get_text().strip() if beschreibung_container else "" ausstattung_container = container.find_all("pre", {"class":"is24qa-ausstattung text-content short-text"}) or "" ausstattung = ausstattung_container[0].get_text().strip() if ausstattung_container else "" lage_container = container.find_all("pre", {"class":"is24qa-lage text-content short-text"}) or "" lage = lage_container[0].get_text().strip() if lage_container else "" except: print("Es gab einen Fehler") f.write(objektid + "##" + titel + "##" + adresse + "##" + criteria.replace(" ", ";") + "##" + preis.replace(" ", ";") + "##" + energie.replace(" ", ";") + "##" + re.sub(r'\n+', ' ', beschreibung) + "##" + re.sub(r'\n+', ' ', ausstattung) + "##" + re.sub(r'\n+', ' ', lage) + "\n") ... 的初学者。我希望在没有超时的情况下在后台运行一些进程。该过程的某些部分必须递归运行,其他部分每天运行(对于lucene搜索引擎中的索引数据)。

现在我正在使用一个在每个请求的头部运行的动作控制器,但某些进程以超时状态结束。

作为一种解决方法,我将AspNet Core超时设置为很长时间,但这不是一个好的解决方案。

1 个答案:

答案 0 :(得分:2)

您必须使用实现IHostedService接口的BackGround Process。像这样:

public abstract class BackgroundService : IHostedService, IDisposable
    {
        private Task _executingTask;
        private readonly CancellationTokenSource _stoppingCts =
                                                       new CancellationTokenSource();

        protected abstract Task ExecuteAsync(CancellationToken stoppingToken);

        public virtual Task StartAsync(CancellationToken cancellationToken)
        {
            // Store the task we're executing
            _executingTask = ExecuteAsync(_stoppingCts.Token);

            // If the task is completed then return it,
            // this will bubble cancellation and failure to the caller
            if (_executingTask.IsCompleted)
            {
                return _executingTask;
            }

            // Otherwise it's running
            return Task.CompletedTask;
        }

        public virtual async Task StopAsync(CancellationToken cancellationToken)
        {
            // Stop called without start
            if (_executingTask == null)
            {
                return;
            }

            try
            {
                // Signal cancellation to the executing method
                _stoppingCts.Cancel();
            }
            finally
            {
                // Wait until the task completes or the stop token triggers
                await Task.WhenAny(_executingTask, Task.Delay(Timeout.Infinite,
                                                              cancellationToken));
            }
        }

        public virtual void Dispose()
        {
            _stoppingCts.Cancel();
        }
    }