【问题标题】:run process on AspNetCore Applications without timeout在 AspNetCore 应用程序上运行进程而不会超时
【发布时间】:2018-05-25 01:28:05
【问题描述】:

我是AspNet Core 的初学者。我想在后台运行一些进程而不会超时。该过程的某些部分必须递归运行,而其他部分每天运行(用于 lucene 搜索引擎中的索引数据)。

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

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

【问题讨论】:

    标签: c# asp.net-core


    【解决方案1】:

    您必须使用 IHostedService 接口实现的后台进程。像这样:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-13
      • 1970-01-01
      • 1970-01-01
      • 2015-07-12
      • 2017-04-24
      • 1970-01-01
      • 1970-01-01
      • 2012-05-31
      相关资源
      最近更新 更多