I am currently trying to decide between the two options below. I am using the Worker
class, which inherits from BackgroundService
. The way I see it, I have three options to handle cleaning up my windows service when a shutdown request is received:
- In
ExecuteAsync(CancellationToken stoppingToken)
catchTaskCanceledException
, log, perform cleanup infinally{}
as below:
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_Service1.Start();
_Service2.Start();
try
{
while (!stoppingToken.IsCancellationRequested)
{
await Task.Delay(500, stoppingToken);
}
}
catch (TaskCanceledException)
{
_Logger?.LogInformation("Task cancelled. Stopping service");
}
finally
{
_Service1.WaitStop();
_Service2.WaitStop();
_Logger?.LogInformation("Service stopped");
}
}
- Override
StopAsync(CancellationToken cancellationToken)
, clean up, thenawait base.StopAsync(cancellationToken)
as below:
public override async Task StopAsync(CancellationToken cancellationToken)
{
_Service1.WaitStop();
_Service2.WaitStop();
await base.StopAsync(cancellationToken);
}
Which would be the best/preferred way to do this?
Additionally: Should I go for performing cleanup in ExecuteAsync, is it better to do so in the finally block or after the catch block (without finally)?