Background Service Vs Hosted Service

0 views
Skip to first unread message

Agalia Valcin

unread,
Aug 5, 2024, 12:39:19 AM8/5/24
to bihechugi
Thisinformation relates to a pre-release product that may be substantially modified before it's commercially released. Microsoft makes no warranties, express or implied, with respect to the information provided here.

In ASP.NET Core, background tasks can be implemented as hosted services. A hosted service is a class with background task logic that implements the IHostedService interface. This article provides three hosted service examples:


Use the Worker Service (worker) template with the dotnet new command from a command shell. In the following example, a Worker Service app is created named ContosoWorker. A folder for the ContosoWorker app is created automatically when the command is executed.


An app based on the Worker Service template uses the Microsoft.NET.Sdk.Worker SDK and has an explicit package reference to the Microsoft.Extensions.Hosting package. For example, see the sample app's project file (BackgroundTasksSample.csproj).


For web apps that use the Microsoft.NET.Sdk.Web SDK, the Microsoft.Extensions.Hosting package is referenced implicitly from the shared framework. An explicit package reference in the app's project file isn't required.


The hosted service is activated once at app startup and gracefully shut down at app shutdown. If an error is thrown during background task execution, Dispose should be called even if StopAsync isn't called.


ExecuteAsync(CancellationToken) is called to run the background service. The implementation returns a Task that represents the entire lifetime of the background service. No further services are started until ExecuteAsync becomes asynchronous, such as by calling await. Avoid performing long, blocking initialization work in ExecuteAsync. The host blocks in StopAsync(CancellationToken) waiting for ExecuteAsync to complete.


The cancellation token is triggered when IHostedService.StopAsync is called. Your implementation of ExecuteAsync should finish promptly when the cancellation token is fired in order to gracefully shut down the service. Otherwise, the service ungracefully shuts down at the shutdown timeout. For more information, see the IHostedService interface section.


A timed background task makes use of the System.Threading.Timer class. The timer triggers the task's DoWork method. The timer is disabled on StopAsync and disposed when the service container is disposed on Dispose:


The Timer doesn't wait for previous executions of DoWork to finish, so the approach shown might not be suitable for every scenario. Interlocked.Increment is used to increment the execution counter as an atomic operation, which ensures that multiple threads don't update executionCount concurrently.


The default behavior can be changed so that the hosted service's StartAsync runs after the app's pipeline has been configured and ApplicationStarted is called. To change the default behavior, add the hosted service (VideosWatcher in the following example) after calling ConfigureWebHostDefaults:


StartAsync should be limited to short running tasks because hosted services are run sequentially, and no further services are started until StartAsync runs to completion. Long running tasks should be placed in ExecuteAsync. For more information, see the source to BackgroundService.


The Host is a container which offers rich built-in services such as Dependency Injection, Configuration, Logging, Host Services and others. The NET 6 offers Generic DefaultHost which can be configured to handle the activities as per your use case. Two major variations of the Host are:


Think of it as Airbnb Host who keeps the property ready to serve when the guests arrive.The property offers a different set of services and allows you to bring your own services. The lifetime of such services depends upon the contract, which the Host controls.


A service that performs the work in the background mostly does not offer an interface to interact. In technical terms, any reference type object which implements the IHostedService interface is a background/hosted/worker service.


Terms such as Worker, Windows Service, and Background Task refer to HostedService based on context.In Windows Server, Widows Service is how you deploy a Hosted Service. Background Task or Hosted service runs as part of .NET Web Host, and it runs in the same operating system process.


The StartAsync method should not block the execution because if multiple hosted services exist in the Host, the following services will not start until the first service finish the start. We will see a demo of such behavior later in the post. If your task is long-running, you can use a await Task.Yield() to unblock the StartAsync method. The .NET will move to the next service as soon as the task becomes awaitable.


BackgroundService is an abstract class, and implements IHostedService.The BackgroundService encapsulates the implementation of StartAsync, StopAsync, creation of CancellationTokenSource and disposal of resources. In other words, it is an excellent example of the Template Method Pattern.


The ExecuteAsync is an abstract method which will be called when the hosted service starts with the CancellationToken, which offers us to complete our work when Token cancellation is not requested.The cancellation can happen if you press ctrl + c or if the Host decides to stop the Hosted Services gracefully.

3a8082e126
Reply all
Reply to author
Forward
0 new messages