我是 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/