C#C
C#2y ago
Memw*

HostedService stopping infinitely

I'm making a discord bot that has some other services running and I don't seem to get why when I try to stop my application it just be Application is being stopped I'd assume some process is blocking but I don't see any way of debugging that, I checked everywhere but I don't see anything

the potential problem might be that

Program.cs
private static async Task Main()
{
    StartApplication();

    CancellationTokenSource ctSource;

    do
    {
        ctSource = Services.GetRequiredService<CancellationTokenSource>();
        await Task.Delay(TimeSpan.FromSeconds(1), ctSource.Token);
    } while (!ctSource.IsCancellationRequested);
}

public static void StartApplication()
    => Provider.Start();

private static IHost CreateProvider()
    {
        DiscordSocketClient client = new(new DiscordSocketConfig
        {
            AlwaysDownloadUsers = true,
            AuditLogCacheSize = 1000,
            GatewayIntents = GatewayIntents.All
        });
        
        // TODO: change to type.
        EnvContext settings = new EnvContext()
            .AddVariablesFrom(File.Open(".env", FileMode.Open), true);
        
        HostApplicationBuilder builder = new HostApplicationBuilder();
        
        builder.Services
            .AddSingleton(client)
            .AddSingleton(settings)
            .AddSingleton(x => new InteractionService(x.GetRequiredService<DiscordSocketClient>()))
            .AddSingleton<CancellationTokenSource>()
            .AddHostedService<ExceptionCatcherService>()
            .AddHostedService<BotStartService>()
            .BuildServiceProvider();

        return builder.Build();
    }


and I have a service running that's ExceptionCatcherService which should log any unhandled exception and restart the HostedService

    public override async Task StopAsync(CancellationToken cancellationToken)
    {
        await base.StopAsync(cancellationToken);
        await ct.CancelAsync();
    }
Was this page helpful?