Home > Back-end >  .NET - HostedService is blocking the rest of the API from running
.NET - HostedService is blocking the rest of the API from running

Time:04-11

I have a background service class that opens a subscriptions and listens indefinitely, and I believe this is stopping the rest of the API from running. I cannot call endpoints, the swagger page never boots up, but the background service runs.

I have services.AddHostedService<BackgroundService>();in the Program.cs file, and that class inherits IHostedService, and within the inherited StartAsync function I call a method that opens and listens to a subscription. This will never end, so it blocks the rest of the API.

How can I solve this problem? I need this subscription to be open when the API starts, forever, but I need to use the API as well. I know it's most likely a concurrency problem but this is a weak point of mine.

Thanks

CodePudding user response:

You can do your stuff asynchronously.

class YourHostedService : IHostedService 
{
   private Task _myLongRunningTask;
   public Task StartAsync(CancellationToken cancellationToken)
   {
      _myLongRunningTask = OpenSubscriptionAndProcessAsync();
      return Task.CompletedTask;
   }

   private async Task OpenSubscriptionAndProcessAsync() 
   {  
       // your code here  
   }

   // [...]
}

The startup of IHostedServices is waiting until StartAsync(...) has completed.

In your case I think you do your stuff all in the StartAsync(...) which will then never finish.

IHostedService Documentation

Other SO Answers

CodePudding user response:

thanks for the feedback! It was very useful.

I ended up not going with a HostedService for this kind of thing, moved it into a service that I call in an endpoint.

Whilst it was still a HostedService, I solved it by creating a new Thread with my method containing the logic in StartAsync, starting that Thread. That solved the blocking issue.

I need to read more about Threads!

  • Related