BackgroundService in .NET Core for long running tasks

Daniel Sagita
2 min readSep 3, 2018

.NET Core 2.1 has a new feature called IHostedService to allow developers to run a background service that can have a managed lifetime to its caller, be it from an ASP.NET Core or a console.

This feature only need a minimal implementation as seen below.

You will then need to register it to the .NET Core dependency injection like below.

var hostBuilder = new HostBuilder()
.ConfigureServices(services =>
services.AddHostedService<WorkerService>());

This is an implementation for .NET Core Console Application. You will find this is similar to the web version which is using WebHostBuilder

You can find out more regarding the usage of HostBuilder through Microsoft documentation here.

Steve Gordon has a great explanation regarding its usage on ASP.NET Core or as a Windows Service. You can read that here and here.

Microsoft sample on the other hand provide several samples regarding common usage pattern for this IHostedService.

  • Timed background tasks
  • Consuming a scoped service in a background task
  • Queued background tasks

Actually this is where I made a mistake by not reading the samples from Microsoft thoroughly. A simple glance will tell you that all you need to do is implement a IHostedService and register it and you are done with it.

I would then implement a long-running background service namely a long polling of sort to be like below.

That kind of implementation will actually block the service and stop everything else. At first I thought that IHostedService is going to run in the background, so we are free to do the loop inside the StartAsync method. IHostedService doesn’t provide any other method that specify where to run the long running implementation.

And so it turns out you need to implement another type called BackgroundService for your IHostedService implementation. This part is actually described in the Microsoft sample above for the “Queued background tasks” part.

What you do is then use this type for your implementation and override its ExecuteAsync method like below.

You will then get a log stating that the “Application started”.

If you don’t get that, then that means you are still blocking the application and will need to review your code again.

The BackgroundService is actually creating another Task to run the loop above, as shown below.

Summary

BackgroundService by the .NET Core team provided you a way to run a long running job trivially and so you can focus on the business logic inside that service. Although some issue may occur if you are not careful with how you implement the IHostedService

Hopefully this serves as a lesson so that at least I myself not making another mistake implementing this background service.

--

--