ASP.NET Core Background Service under the hood

Khanh Nguyen • 10 October 2021 • 

ASP.NET Core.Net CoreBackground Service

From the old days, we're farmiliar with window service that provided by Window. But now, in the conainer area, the term window service was not suitable one. So what's its alternative ?

Meet a candidate Background tasks with hosted services.

Sound fancy, but does it ?#

It's a simple object, got executed by a task. That's all.

A little weird ? After taking a tour from the link above ? Let's look at the code then.

public interface IHostedService
{
  Task StartAsync(CancellationToken cancellationToken);
  Task StopAsync(CancellationToken cancellationToken);
}

public abstract class BackgroundService : IHostedService, IDisposable
{
  //... Implementation
}

Meet our protagonist, IHostedService. A simple interface marker that have StartAsync and StopAsync method. Usually, we create a background service in ASP.NET Core by inherit from BackgroundService, then override StartAsync method, and finally register it on startup. and that's done. So, we have the object.

But where was the task ? Well, the framework did it for us.

CreateHostBuilder(args).Build().Run()

Run() method would actually start the webhost for us. Then, take a little attention on this line

_hostedServiceExecutor = _applicationServices.GetRequiredService<HostedServiceExecutor>();

That's where magic happen. And this is how HostedServiceExecutor implemented under the hood. What she does is just simply took all objects that implement IHostedService from DI container, then execute it with a task.

Just as simple as that.

I have some very long running task to run, should I use it with ASP.NET Core ?#

Seems like background service indicate that it was born to handle these type of missions. And she actually does, except for one thing, holding thread in ASP.NET Core was not such a good idea.

Each request require at least a thread to handle its job, which would take from the thread pool. If the thread are hold for too long, the application will suffer performance penalty.

But don't be worry, the circumstance rarely happen, for almost every use cases. But something like processing heavy text files or images would deserve much better consideration.


Khanh Nguyen

Web developer & .Net lover