Search code examples
asp.net-core-webapiasp.net-core-hosted-services

Where to start monitoring queue in ASP.NET Core hosted service


I'm following this example for a queued hosted service to add this to an ASP.NET Core application, and it's not clear to me where StartMonitorLoop should be called. I ended up modifying it to be EnsureMonitorLoop, added a check so that it's the call to Task.Run is only made once, added a MonitorLoop parameter to constructor for my API controller, and called EnsureMonitorLoop from there. It smells kind of funny to me that the API controller constructor should be kicking off monitoring the queue. The example Program.cs seems is very different from the one generated for me by Visual Studio. Mine uses the WebHost.CreateDefaultBuilder(args).UseStartup<Startup> approach. That is where they call StartMonitorLoop.

Where is the correct place to call StartMonitorLoop, and why? Thanks!


Solution

  • The docs aren't super clear here, but MonitorLoop is not actually part of this. It's an example service for use in a console app, simply to demonstrate how the queued background worker works. You can take some inspiration from this class for your app, but the concept of StartMonitorLoop doesn't apply to ASP.NET Core at all.

    Just to be a bit more clear: in actual practice you would inject IBackgroundTaskQueue into a controller class, for example, and then add some task to that, just like MonitorLoop does (without all the key input jazz). You wouldn't actually have MonitorLoop or anything like it though.