首页 新闻 会员 周边 捐助

C# 中实现 IDisposable 接口出现 CA1063 与 CA1816 代码规范警告

0
悬赏园豆:30 [已解决问题] 解决于 2025-06-08 16:38

下面的 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.

请问如何以最简单的方法消除这个警告?

dudu的主页 dudu | 高人七级 | 园豆:24691
提问于:2025-06-08 16:27
< >
分享
最佳答案
0

提问后找到了答案,提问前没有仔细看警告信息中的一句话 mark the type as sealed,在 class 之前加上 sealed 就轻松解决了

public sealed class RedisCheckHostedService : IHostedService, IDisposable
{
    // ...
}
dudu | 高人七级 |园豆:24691 | 2025-06-08 16:38
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册