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

时间:2021-02-26 08:16:17

标签: c# events 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;
    }
}

0 个答案:

没有答案
相关问题