C#C
C#4y ago
kunio_kun

ASP NET Core 6 Launch without Debugging doesn't block Background Service but Debug Does

Hi,

I'm trying to have a ASP.NET Core BackgroundService run really in background, i mean really don't interrupt with request/response part and I've been trying many stuff

    private Thread? _workerThread;

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        Logger.LogInformation("Monitoring Event Triggering Start");
        _workerThread = new Thread(() =>
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                if (EventQueue.Count == 0) continue;
                var monitoringEvent = EventQueue.Dequeue();
                using (var scope = ServiceProvider.CreateScope())
                {
                    var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
                    db.MonitoringEvents.Add(monitoringEvent);
                    db.SaveChanges();
                }

                // TODO Trigger events, notifications
                Logger.LogInformation($"{monitoringEvent.DateTime} Rule {monitoringEvent.Message} triggered");
            }
        });
        _workerThread.IsBackground = true;
        _workerThread.Start();
    }


That is the code i currently have, and one weird thing is if I debug the code, the service blocks the program execution, while if I use run, it doesn't block and continue as expected.

Is there any mistakes there?
Also, is there other ways to do this? I tried Task.Run(), Task.Factory.StartNew() and they all block.

I'm on Jetbrains Rider on Ubuntu 20.04 if that matters for the threading part.

Thanks in advance!
Was this page helpful?