I have following implementation for one of an abstract class but getting warning from sonarqube code analysis
public abstract class BackgroundService : IHostedService, IDisposable
{
private bool _disposedValue;//https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/implementing-dispose
private Task _executingTask;
private readonly CancellationTokenSource _stoppingCts = new CancellationTokenSource();
protected abstract Task ExecuteAsync(CancellationToken stoppingToken);
public virtual Task StartAsync(CancellationToken cancellationToken)
{
_executingTask = ExecuteAsync(_stoppingCts.Token);
if (_executingTask.IsCompleted)
{
return _executingTask;
}
return Task.CompletedTask;
}
public virtual async Task StopAsync(CancellationToken cancellationToken)
{
if (_executingTask == null)
{
return;
}
try
{
_stoppingCts.Cancel();
}
finally
{
await Task.WhenAny(_executingTask, Task.Delay(Timeout.Infinite, cancellationToken));
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected void Dispose(bool disposing)//todo kamran
{
if (_disposedValue)
{
return;
}
if (disposing)
{
_stoppingCts.Cancel();
}
_disposedValue = true;
}
~BackgroundService()
{
Dispose(false);
}
}
sonar cube error is
Fix this implementation of 'IDisposable' to conform to the dispose pattern.
Code Smell
Provide 'protected' overridable implementation of 'Dispose(bool)' on 'BackgroundService' or mark the type as 'sealed'.
'BackgroundService.Dispose()' should not be 'virtual' or 'abstract'.
'BackgroundService.Dispose()' should also call 'Dispose(true)'.