Slot 28 - 29-Background Tasks With Worker Service

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 37

Background Tasks with Worker Service

Objectives
 Overview Worker Service .NET
 How to implement a Background Task by Worker Service
 Overview Windows Service
 Demo create Worker Service to consume ASP.NET Core Web API
 Demo to publish Worker Service as a Windows Service

05/20/2024 2
Overview Worker Service .NET
Understanding Worker Service .NET
 A worker service is a .NET project built using a template which supplies a few
useful features that turn a regular console application into something more
powerful
 A worker service runs on top of the concept of a host, which maintains the
lifetime of the application. The host also makes available some familiar features,
such as dependency injection, logging and configuration
 Worker services will generally be long-running services, performing some
regularly occurring workload such as:
 Processing messages/events from a queue, service bus or event stream
 Reacting to file changes in an object/file store
 Aggregating data from a data store
 Enriching data in data ingestion pipelines
 Formatting and cleansing of AI/ML datasets
05/20/2024 4
Understanding Worker Service .NET
 It’s also possible to develop a worker service which performs a process from
start to finish and then shuts down. Coupled with a scheduler, this can support
periodical batch workloads
 For example, every hour the service is started by the scheduler, calculates some
aggregate totals and then shuts down
 Worker services do not have a user interface, nor will they support direct user
interaction. They are particularly applicable when designing a microservices
architecture. Here responsibilities are often split into distinct, separately
deployable and scalable services
05/20/2024 5
Understanding Worker Service .NET
 Use a host to maintain the lifetime of the console application until the host is
signalled to shut down. Turning a console application into a long-running service

 Include features common to ASP.NET Core such and dependency injection,


logging and configuration

 Perform periodic and long-running workloads

 Background tasks can be implemented in two ways: Implementing


IHostedService Interface and Inheriting BackgroundService Class
05/20/2024 6
The BackgroundService Class
 BackgroundService is an abstract base class for implementing a long-running
IHostedService. Using BackgroundService class we can write less code as
compared to IHostedService
 The following table describes some of the key methods:
Method Description
StartAsync(CancellationToken) Triggered when the application host is ready to start the service
StopAsync(CancellationToken) Triggered when the application host is performing a graceful shutdown
Performs application-defined tasks associated with freeing, releasing, or resetting
Dispose()
unmanaged resources
Determines whether the specified object is equal to the current object.
Equals(Object)
(Inherited from Object)
This method is called when the IHostedService starts. The implementation should
ExecuteAsync(CancellationToken) return a task that represents the lifetime of the long running operation(s) being
performed
05/20/2024 7
The Worker Service Template Provide
 The worker service template includes useful foundational components, like
dependency injection, by default so that we can focus on building our business
logic on top. It includes a host which manages the lifecycle of the application
 The worker service template is reasonably basic and includes just three core
files:
 Program.cs: The first of which is a
Program class. This class consists of the
required Main method entry point
for .NET console applications. The .NET
runtime expects to locate this method
within the Program class when it starts
your .NET application
05/20/2024 8
The Worker Service Template Provide
 appsettings.json: It is one of the common
sources for application configuration. The host
is configured to load application configuration
from several sources when the application
starts using any registered configuration
providers
 Worker.cs: The Worker class is something
new which you will not find in the default
ASP.NET Core project template. This is where
the magic of hosted services, combined with
the host, provide the basis of a worker service
05/20/2024 9
Demo 01: Create a Worker Service
using Visual Studio.NET
1. Open Visual Studio.NET , File | New | Project
1

05/20/2024 11
2. Fill out Project name: MyWPFApp and Location then click Next

05/20/2024 12
3. Choose Target Framework: .NET 5.0 (Current) then click Create

05/20/2024 13
4. Run the project

05/20/2024 14
Demo 02: Worker Service and Web API
Worker Service Demo-02
 Create a background task that use HttpClient to call a API service to retrieve
the current exchange rate between various currencies, and print the result
1.Open the Visual Studio.NET then create ASP.NET Web API Project named
ExchangeRateService

05/20/2024 16
Worker Service Demo-02

05/20/2024 17
Worker Service Demo-02

05/20/2024 18
2.Write codes for the ExchangeRateService project as follows:

05/20/2024 19
3. Right-click on the project, select Open in Terminal. On Developer PowerShell dialog,
execute the following command to run Web API project

05/20/2024 20
4. Open the web browser and enter the following link to test GetLatestRates method with Swagger :
http://localhost:5000/swagger/index.html

05/20/2024 21
5. Create Worker Service Project named DemoWorkerService02 to consume
ExchangeRateService project
6. Install Microsoft.Extensions.Http package from NuGet
7. Write codes for CurrencyExchange.cs and Program.cs as follows:

05/20/2024 22
8. Write codes for Worker.cs as follows:

05/20/2024 23
9. Run DemoWorkerService02 project

05/20/2024 24
Introduction to Windows Service
 Microsoft Windows services, formerly known as NT services, enable us to
create long-running executable applications that run in their own Windows
sessions
 These services can be automatically started when the computer boots, can be
paused and restarted, and do not show any user interface
 These features make services ideal for use on a server or whenever we need
long-running functionality that does not interfere with other users who are
working on the same computer
 We can also run services in the security context of a specific user account that
is different from the logged-on user or the default computer account
05/20/2024 25
Introduction to Windows Service

05/20/2024 26
Windows Service and Systemd on Linux
 .NET Framework developers are probably familiar with Windows Service apps

 Before .NET Core and .NET 5+, developers who relied on .NET Framework

could create Windows Services to perform background tasks or execute long-

running processes

 This functionality is still available and we can create Worker Services that run

as a Windows Service on Windows and Systemd on Linux


05/20/2024 27
Demo 03: Publish a Worker Service as a
Windows Service
1.Create Worker Service Project named DemoWorkerService03 to consume
ExchangeRateService project (refer to Demo 02)
2.Install Microsoft.Extensions.Http and Microsoft.Extensions.Hosting.WindowsServices
package from NuGet
3.Write codes for CurrencyExchange.cs and Program.cs as follows:

05/20/2024 29
4. Write codes for Worker.cs as follows:
5. Right-click on the project, select Open in Terminal. On Developer PowerShell dialog,
execute the following command to publish project :

dotnet publish -c Release


6. Right-click on the ExchangeRateService project, select Open in Terminal. On
Developer PowerShell dialog, execute the following command to run Web API project

05/20/2024 32
7. Run DemoWorkerService03 project , then view ExchangeRate.txt file

05/20/2024 33
8. Create Windows Service from DemoWorkerService03 project
 Open a Command Prompt as Administrator, and install the application using the Windows sc utility
( refer to publish folder in Step 5)

sc create "My Service" BinPath="D:\publish\Demo_WorkerService_03.exe"

05/20/2024 34
9. Open Services dialog from Control Panel | All Control Panel Items | Administrative
Tools and select “My Service” then right-click | press Start to start service

05/20/2024 35
10. Open ExchangeRate.txt file to view data. The file size will increase every 5 seconds

11. Stop “My Service” and use the following command to remove it :

05/20/2024 36
Summary
 Concepts were introduced:
 Overview Worker Service .NET

 How to implement a Background Task by Worker Service

 Overview Windows Service

 Demo create Worker Service to consume ASP.NET Core Web API

 Demo to publish Worker Service as a Windows Service

37

You might also like