Reputation: 83
I have a BackgroundService called Worker, which I override the ExecuteAsync method to run something each 10 seconds. Sometimes, what I run lasts very long. In this scenario, I want to kill what I am running, then rerun it. How can I achieve this?
My BackgroundService is as follows:
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);
}
Upvotes: 3
Views: 1556
Reputation: 2227
You could do something along these lines:
protected override async Task ExecuteAsync(CancellationToken stoppingToken) {
var cancellationSource = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken);
cancellationSource.CancelAfter(10000);
return Task.Run(() => task.Execute(cancellationSource.Token));
}
If you want to handle execptions and/or await the task then you can but this is a simple example.
Upvotes: 2