c# - 在没有超时的情况下在 AspNetCore 应用程序上运行进程

标签 c# asp.net-core

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

现在我正在使用一个在每个请求的头部运行的 Action Controller ,但是一些进程以超时状态结束。

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

最佳答案

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

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

关于c# - 在没有超时的情况下在 AspNetCore 应用程序上运行进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50513574/

相关文章:

c# - vNext 中间件抛出 "Unable to locate suitable constructor for type ' XXX'”错误

c# - NHibernate 标准按一天中的时间搜索

c# 在另一个 List<T> 中搜索 List<t>

c# - 在 C# 中是否有简写 If-Then-Else 的版本(cond?VB.Net 中的 : b),?

c# - 如何检测单击了数据列表项的哪个元素?

c# - 进行 SSL 连接时需要主机名验证

jquery - 确认删除模式/对话框,Twitter Bootstrap 不起作用

asp.net-core - 使用 asp-validation-for 而不绑定(bind)到模型属性

javascript - 如何将dom元素值传递给ajax请求(html.Pagedlist参数)

C# 在静态上下文中访问 IModelMetaDataProvider - IHtmlHelper