C#
C#

help

Root Question Message

kunio_kun
kunio_kun10/24/2022
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!
Kouhai
Kouhai10/24/2022
There's no way to achieve that, all threads are halted when reaching a breakpoint
kunio_kun
kunio_kun10/24/2022
ah it's not that i put any breakpoints there
kunio_kun
kunio_kun10/24/2022
i meant this buttons
kunio_kun
kunio_kun10/24/2022
If i started it with Debug, it never made it to the next service
kunio_kun
kunio_kun10/24/2022
but it works correctly with Run
kunio_kun
kunio_kun10/24/2022
I have been investigating for a few hours and with Jetbrains' IDE i found that it doesn't get to the TryExecuteBackgroundServiceAsync() and the foreach loop stucks
Kouhai
Kouhai10/24/2022
That's weird, do you have specific code that runs for development vs production builds?
Does the foreach loop even execute or is _hostedServices empty?
kunio_kun
kunio_kun10/24/2022
it is not empty
kunio_kun
kunio_kun10/24/2022
I have 2 background services and with the debugger breakpoint it didn't evaluate to true for the first background service (this one)
kunio_kun
kunio_kun10/24/2022
also i dont have any specific code that runs on different configuration
Kouhai
Kouhai10/24/2022
does hostedService.StartAsync await infinitely? (or it's not even reached)
kunio_kun
kunio_kun10/24/2022
at least not in my own code (non library), and not in this service
kunio_kun
kunio_kun10/24/2022
does it refer to this backgroundservice?
kunio_kun
kunio_kun10/24/2022
it is reached
kunio_kun
kunio_kun10/24/2022
it does have infinite loop
kunio_kun
kunio_kun10/24/2022
I have updated the code to this
kunio_kun
kunio_kun10/24/2022
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        if (LongRunningTask is not null) throw new InvalidOperationException("Already running");

        Logger.LogInformation("Monitoring Event Triggering Start");
        LongRunningTask = Task.Run(async () =>
            {
                while (!stoppingToken.IsCancellationRequested)
                {
                    if (EventQueue.Count == 0) continue;
                    var monitoringEvent = EventQueue.Dequeue();
                    using (var scope = ServiceProvider.CreateScope())
                    {
                        var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
                        await db.MonitoringEvents.AddAsync(monitoringEvent, stoppingToken);
                        await db.SaveChangesAsync(stoppingToken);
                    }

                    // TODO Trigger events, notifications
                    Logger.LogInformation($"{monitoringEvent.DateTime} Rule {monitoringEvent.Message} triggered");
                }
            },
            stoppingToken
        );
        Logger.LogInformation("Task is running");
    }
kunio_kun
kunio_kun10/24/2022
ooh
kunio_kun
kunio_kun10/24/2022
kunio_kun
kunio_kun10/24/2022
now wonder if it blocks somewhere else
kunio_kun
kunio_kun10/24/2022
but according to the debugger it doesnt even get to the second backgroundservice i have
Kouhai
Kouhai10/24/2022
Based on these logs, I assume both services seem to be started
kunio_kun
kunio_kun10/24/2022
i will try putting breakpoint again
kunio_kun
kunio_kun10/24/2022
kunio_kun
kunio_kun10/24/2022
these are the hostedServices
kunio_kun
kunio_kun10/24/2022
kunio_kun
kunio_kun10/24/2022
kunio_kun
kunio_kun10/24/2022
kunio_kun
kunio_kun10/24/2022
the next step after the last picture is nowhere
kunio_kun
kunio_kun10/24/2022
and the log is also stuck here
kunio_kun
kunio_kun10/24/2022
that was Host.cs, class Host in Microsoft.Extensions.Hosting.Internal
kunio_kun
kunio_kun10/24/2022
but i mean even having breakpoints vs no breakpoints on debug has different result?
Kouhai
Kouhai10/24/2022
Hmm so it's stuck after calling StartAsync on the MonitoringEventTriggeringService, I'm not sure if Host.cs has any conditions for production vs development but I doubt that
kunio_kun
kunio_kun10/24/2022
it does get to
if (hostedService is BackgroundService backgroundService)
kunio_kun
kunio_kun10/24/2022
and then next step is nowhere
Kouhai
Kouhai10/24/2022
Oh
kunio_kun
kunio_kun10/24/2022
okay just tried it again
kunio_kun
kunio_kun10/24/2022
this time the next step was the closing curly brackets of the foreach loop, as if the hostedService is not BackgroundService
kunio_kun
kunio_kun10/24/2022
got to the next enumeration (is it?) in the in _hostedService and then next step is nowhere
Kouhai
Kouhai10/24/2022
The condition hostedService is BackgroundService backgroundServic fails?
Hmm even if it fails it should continue looping
kunio_kun
kunio_kun10/24/2022
just tried again
kunio_kun
kunio_kun10/24/2022
it didnt continue after the hostedService is BackgroundService part
kunio_kun
kunio_kun10/24/2022
i mean even if it fails, it may be throwing something right?
Kouhai
Kouhai10/24/2022
But what would throw?
is T just checks if the instance is of that type, if so it would run the code inside the braces
kunio_kun
kunio_kun10/24/2022
while it does inherit from BackgroundService
Kouhai
Kouhai10/24/2022
idk if it would help, but what version of ASP.NET Core are you using
kunio_kun
kunio_kun10/24/2022
ASP.NET Core MVC 6
kunio_kun
kunio_kun10/24/2022
dotnet --version
6.0.402
kunio_kun
kunio_kun10/24/2022
Linux 5.15.0-52-generic #58~20.04.1-Ubuntu SMP Thu Oct 13 13:09:46 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux
kunio_kun
kunio_kun10/24/2022
maybe i should also try it on Windows and see if it happens
ContactFrequently Asked QuestionsJoin The DiscordBugs & Feature RequestsTerms & Privacy