我有一个名为“Worker”的BackgroundService,我覆盖了ExecuteAsync方法以每10秒运行一些东西。有时候,我运行的内容持续时间很长。在这种情况下,我想要终止正在运行的内容,然后重新运行它。我该如何实现?
我的BackgroundService如下所示:
public class Worker : BackgroundService {
private readonly ITask task;
private readonly IHostApplicationLifetime appLifeTime;
public Worker(ITask task, IHostApplicationLifetime appLifeTime) {
this.task = task;
this.appLifeTime = appLifeTime;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken) {
while (!stoppingToken.IsCancellationRequested)
{
try {
this.task.Execute(stoppingToken);
} catch (Exception e) {
this.appLifeTime.StopApplication();
}
await Task.Delay(10000, stoppingToken);
}
}
}
public interface ITask {
void Execute(CancellationToken stoppingToken);
}