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



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

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

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

您必须使用实现 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();
}
}

最新更新