下面的 RedisCheckHostedService 类实现了 IDisposable 接口
public class RedisCheckHostedService : IHostedService, IDisposable
{
private Timer? _timer = null;
private int _defaultRedisFailures;
public Task StartAsync(CancellationToken stoppingToken)
{
_timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromSeconds(30));
return Task.CompletedTask;
}
private void DoWork(object? state)
{ }
public Task StopAsync(CancellationToken stoppingToken)
{
_timer?.Change(Timeout.Infinite, 0);
return Task.CompletedTask;
}
public void Dispose()
{
_timer?.Dispose();
}
}
却出现两个代码规范警告
CA1063: Modify 'RedisCheckHostedService.Dispose' so that it calls Dispose(true), then calls GC.SuppressFinalize on the current object instance ('this' or 'Me' in Visual Basic), and then returns
CA1816: Provide an overridable implementation of Dispose(bool) on 'RedisCheckHostedService' or mark the type as sealed. A call to Dispose(false) should only clean up native resources. A call to Dispose(true) should clean up both managed and native resources.
请问如何以最简单的方法消除这个警告?
提问后找到了答案,提问前没有仔细看警告信息中的一句话 mark the type as sealed
,在 class
之前加上 sealed
就轻松解决了
public sealed class RedisCheckHostedService : IHostedService, IDisposable
{
// ...
}