Building a windows service with .net core worker services - Microsoft Technologies, Azure and .net Tutorials

Latest

Saturday, June 20, 2020

Building a windows service with .net core worker services

Asp.net core 3 brings a very interesting new feature “Worker Service”. It is an Asp.net core template that allows you to create hosted long-running background services. These background services implements the IHostedService interface, so they are called hosted services.

Worker services are the perfect use case for any background processing such as components in an ETL pipeline, processing messages from a Kafka, Rabbit or SQS queue. Perhaps you want to run customised health checks on your systems. Any processing job you can think of where you need a simple, straightforward framework to do so, Worker Services now has you covered.

Worker Service template

The ASP.NET Core Worker Service template provides a starting point for writing long running service apps. An app created from the Worker Service template specifies the Worker SDK in its project file.

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


Worker service implements the BackgroundService

BackgroundService base class

BackgroundService is a base class for implementing a long running IHostedService.

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.

Getting Started

1.     Open visual studio and create new project. Give the project name and create the worker service.

2.     After creating worker service in solution explorer you will get the following files.



3.     Open the Program.cs file you will get the following function

In this we have two methods, Main which is the entry point of our application and CreateHostBuilder which will bootstrap our application, Configure our services and setup any dependencies that we need.

The CreateHostBuilder is where you can add your configuration management, IoC or any additional startup configuration you may need.

The Worker

The template has already provided an example of a basic worker service, with IoC and its own managed lifecycle.

The template utilises IoC to inject a logger into our service and manages its lifecycle via a CancellationToken that’s passed in by the .NET Core framework. Most worker services wouldn’t differ too much from this implementation unless of course, you were using an external source (i.e. feature flag) to handle the lifecycle.

You can also override the function StartAsync and StopAsync function.


StartAsync(CancellationToken): StartAsync contains the logic to start the background task.StartAsync is called before:

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.

StopAsync(CancellationToken): Triggered when the host is performing a graceful shutdown.StopAsnc contains the logic to end the background task. Implement IDisposable and finalizers (destructors) to dispose of any unmanaged resources.

The cancellation token has a default five second timeout to indicate that the shutdown process should no longer be graceful. When cancellation is requested on the token:

  • Any remaining background operations that the app is performing should be aborted.
  • Any methods called in StopAsync should return promptly

However, tasks aren't abandoned after cancellation is requested—the caller awaits all tasks to complete.

If the app shuts down unexpectedly (for example, the app's process fails), StopAsnc might not be called. Therefore, any methods called or operations conducted in StopAsnc might not occur.

To extend the default five second shutdown timeout, set:

  • ShutdownTimeout when using Generic Host.
  • Shutdown timeout host configuration setting when using Web Host.

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 StopAsnc isn't called.


Running the worker

These workers can be run in the same fashion that you’d run a Console Application (or most .NET Core applications)

If you run the application it will continuously displayed the output until cancellation is provided



Running as a windows service

If you’re looking to run as a Windows service, you’ll need to configure the template slightly.

Start by downloading the Microsoft.Extensions.Hosting.WindowsServices NuGet package and adding it to your project

 

Now inside your program.cs add UseWindowsService() to your CreateHostBuilder

 

To host the service as a windows service run the following command.

Open the command prompt as administrator.

Go to your application path

And run the command dotnet restore

After that publish the service using the command

dotnet publish -o ./publish/service

After that host the worker service as a windows service using the following command

sc.exe create MyWorkerService binpath= ./publish/service/TestWorkerService.exe

if all goes well, You should see your Windows Service created and runnable from the service manager!

No comments:

Post a Comment

Metadata in BoxDicom

  Metadata in BoxDicom In BoxDICOM, metadata refers to additional information that can be associated with a file or folder. Metadata in Bo...