我们是否应该使用 Discord.NET 取消订阅已订阅的事件

问题描述

我想知道我们是否应该取消订阅我们订阅的事件,因为他们的 documentation 中的示例没有,但我发现了其他示例,他们确实这样做了。请详细说明原因。

Should I unsubscribe from events?

基本上,如果您确定订阅对象的生命周期将超过事件源,则应该取消订阅,否则会创建不必要的引用。

services.AddSingleton(new discordSocketClient(new discordSocketConfig { LogLevel = LogSeverity.Info }));
services.AddSingleton(new CommandService(new CommandServiceConfig { LogLevel = LogSeverity.Info }));
services.AddHostedService<discordHostedService>();
public class discordHostedService : IHostedService,Idisposable
{
    private readonly ILogger _logger;
    private readonly IServiceProvider _serviceProvider;
    private readonly IOptions<discordOptions> _discordOptions;
    private readonly discordSocketClient _client;
    private readonly CommandService _commands;

    public discordHostedService(
        ILogger logger,IServiceProvider serviceProvider,IOptions<discordOptions> discordOptions,discordSocketClient client,CommandService commands)
    {
        _logger = logger;
        _serviceProvider = serviceProvider;
        _discordOptions = discordOptions;
        _client = client;
        _commands = commands;
    }

    public async Task StartAsync(CancellationToken cancellationToken)
    {
        _client.Ready += ReadyAsync;
        _client.MessageReceived += HandleCommandAsync;
        _client.Log += LogAsync;

        _commands.CommandExecuted += CommandExecutedAsync;
        _commands.Log += LogAsync;

        await _commands.AddModulesAsync(Assembly.GetEntryAssembly(),_serviceProvider);

        await _client.LoginAsync(TokenType.Bot,_discordOptions.Value.Token);
        await _client.StartAsync();
    }

    public async Task StopAsync(CancellationToken cancellationToken)
    {
        await _client.SetStatusAsync(UserStatus.Offline);
        await _client.SetGameAsync(null);
        await _client.StopAsync();

        _client.Ready -= ReadyAsync;
        _client.MessageReceived -= HandleCommandAsync;
        _client.Log -= LogAsync;

        _commands.CommandExecuted -= CommandExecutedAsync;
        _commands.Log -= LogAsync;
    }

    private async Task ReadyAsync()
    {
        ...
    }

    private async Task HandleCommandAsync(SocketMessage messageParam)
    {
        ...
    }

    private Task LogAsync(LogMessage messageParam)
    {
        return Task.CompletedTask;
    }

    public async Task CommandExecutedAsync(Optional<CommandInfo> command,ICommandContext context,IResult result)
    {
        ...
    }

    private bool _disposed = false;

    public void dispose()
    {
        dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void dispose(bool disposing)
    {
        if (_disposed)
            return;

        if (disposing)
        {
            if (_client != null)
            {
                _client.dispose();
            }
        }

        _disposed = true;
    }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)